Get the attachment URL on single.php

The the_attachment_link returns an HTML link, so use this code:

if ( $attachments = get_children( array(
    'post_type'      => 'attachment',
    'post_mime_type' => 'image',
    'numberposts'    => 1,
    'post_status'    => null,
    'post_parent'    => $post->ID
) ) );
foreach ( $attachments as $attachment ) {
    echo wp_get_attachment_link( 
        $attachment->ID, '' , true, false, 'Link to image attachment' 
    );
}

Here I’m passing 5 parameters to function wp_get_attachment_link()

  • First parameter is $attachment->ID to get attachment ID
  • Second parameter '' says not to print image
  • Third parameter true links to attachment page
  • Fourth false parameter tells not to print media parameter
  • The last one is the text you’d like to appear as a link

Leave a Comment