Using WordPress ‘get_the_attachment_link()’ PHP function

The get_the_attachment_link() WordPress PHP function retrieves the HTML content of an attachment image with a link.

Usage

get_the_attachment_link( $id, $fullsize, $max_dims, $permalink );

Parameters

  • $id (int) – Optional. The Post ID.
  • $fullsize (bool) – Optional. Whether to use the full size image. Default: false.
  • $max_dims (array) – Optional. Max image dimensions. Default: false.
  • $permalink (bool) – Optional. Whether to include a permalink to the image. Default: false.

More information

See WordPress Developer Resources: get_the_attachment_link()

Examples

This example retrieves the attachment image’s thumbnail with a link to the full size image.

$image_id = 123; // The attachment image ID
echo get_the_attachment_link( $image_id );

This example retrieves the full size attachment image with a link to the image.

$image_id = 123; // The attachment image ID
echo get_the_attachment_link( $image_id, true );

This example retrieves a resized attachment image with a link to the full size image.

$image_id = 123; // The attachment image ID
$max_dims = array( 300, 300 ); // Max dimensions
echo get_the_attachment_link( $image_id, false, $max_dims );

This example retrieves an attachment image without a link to the full size image.

$image_id = 123; // The attachment image ID
echo get_the_attachment_link( $image_id, false, false, false );

This example retrieves an attachment image with a custom link using a filter.

$image_id = 123; // The attachment image ID
add_filter( 'attachment_link', 'custom_attachment_link', 10, 2 );
function custom_attachment_link( $link, $id ) {
    return 'https://www.example.com/custom-link/' . $id;
}
echo get_the_attachment_link( $image_id );
remove_filter( 'attachment_link', 'custom_attachment_link', 10, 2 );