I’m working on this function of WordPress.

function wp_get_attachment_link( $id = 0, $size="thumbnail", $permalink = false, $icon = false, $text = false ) {
    $id = intval( $id );
    $_post = get_post( $id );

    if ( empty( $_post ) || ( 'attachment' != $_post->post_type ) || ! $url = wp_get_attachment_url( $_post->ID ) )
        return __( 'Missing Attachment' );

    if ( $permalink )
        $url = get_attachment_link( $_post->ID );

    $post_title = esc_attr( $_post->post_title );

    if ( $text )
        $link_text = $text;
    elseif ( $size && 'none' != $size )
        $link_text = wp_get_attachment_image( $id, $size, $icon );
    else
        $link_text="";

    if ( trim( $link_text ) == '' )
        $link_text = $_post->post_title;

    return apply_filters( 'wp_get_attachment_link', "<a href="https://wordpress.stackexchange.com/questions/87262/$url" title="$post_title">$link_text</a>", $id, $size, $permalink, $icon, $text );
}

And I want to modify this line:

return apply_filters( 'wp_get_attachment_link', "<a href="https://wordpress.stackexchange.com/questions/87262/$url" title="$post_title">$link_text</a>", $id, $size, $permalink, $icon, $text );

I want that link can output like this:

<a href="https://wordpress.stackexchange.com/questions/87262/$url" title="$post_title" id='**my_wish_attachment_ID**'>$link_text</a>

Because, default it print out like this:

<a href="http://link-to-image" title="post-title-example"><img src="https://link-to-thumbnail.png" class="attachment-thumbnail" alt="post-title-example" /></a>

I want it print out like this:

<a href="http://link-to-image" title="post-title-example" id='post-title-example'><img src="https://link-to-thumbnail.png" class="attachment-thumbnail" alt="post-title-example" /></a>

My wished attachment ID could be the same with ‘post-title-example’.

I have tried many ways and searched Google a lot. But it doesn’t work.

Can you help me? Thank you.

1 Answer
1

You have to supply a argument count when adding the filter callback, and add the arguments you are expecting to receive to your callback function. Looking at the wp_get_attachment_link source you can tell that 6 arguments is supplied when applying the filters (the link markup and $id, $size, $permalink, $icon, $text). Here’s how you could would do just that:

add_filter('wp_get_attachment_link', 'add_id_into_link', 10, 6);
function add_id_into_link($link, $id = null, $size = null, $permalink = null, $icon = null, $text = null) {
    return str_replace('<a href', '<a id="'. $id .'" href', $link);
} 

Leave a Reply

Your email address will not be published. Required fields are marked *