Add_Filter example for wp_get_attachment_link

Look at the function in wp-includes/post-template.php. There you see what information you can get:

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

Note that you cannot access the $link_text and the $_post object as a standalone variables. Bug? Bug!

In your filter you cannot change the order of the arguments, just the number.

So add_filter( 'wp_get_attachment_link', 'modify_attachment_link', 10, 2 ); will give you the link markup and $id. The highest number of available arguments is 6.

The return value of your function will replace the first argument.

An (untested) example for changing the link URL:

/**
 * Replaces the URL for an attachment link.
 *
 * @param  string $markup     Original link markup
 * @param  int    $id         Post id
 * @param  mixed  $size       Image size, array or string
 * @param  string $permalink  URL
 * @param  bool   $icon       Use an icon?
 * @param  bool   $text       Use text?
 * @return string             New markup
 */
function modify_attachment_link( $markup, $id, $size, $permalink, $icon, $text )
{
    // We need just thumbnails.
    if ( 'thumbnail' !== $size )
    {   // Return the original string untouched.
        return $markup;
    }

    // We have stored the new URL in a post meta field.
    // See https://wordpress.stackexchange.com/q/3097 for an example.
    $new_url = get_post_meta( $id, 'extra_url', TRUE );

    if ( empty ( $new_url ) )
    {   // There is no URL.
        return $markup;
    }

    // Recreate the missing information.
    $_post      = & get_post( $id );
    $post_title = esc_attr( $_post->post_title );

    if ( $text ) 
    {
        $link_text = esc_attr( $text );
    } 
    elseif ( 
           ( is_int( $size )    && $size != 0 ) 
        or ( is_string( $size ) && $size != 'none' ) 
        or $size != FALSE 
    ) 
    {
        $link_text = wp_get_attachment_image( $id, $size, $icon );
    } 
    else 
    {
        $link_text="";
    }

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

    return "<a href="https://wordpress.stackexchange.com/questions/16809/$new_url" title="$post_title">$link_text</a>";
}

add_filter( 'wp_get_attachment_link', 'modify_attachment_link', 10, 6 );

Further reading:

Leave a Comment