Get the attachment URL on single.php

The question:

i’ve been trying to get the attachment URL on single.php, so far this code gets the DIRECT LINK to the image;

<?php

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 '<a target="_blank" href="' . wp_get_attachment_url( $attachment->ID ) . '" rel="nofollow noreferrer noopener">Download Full Size</a>';
}

?>

but instead i want the attachment URL, PLEASE HELP!

The Solutions:

Below are the methods you can try. The first solution is probably the best. Try others if the first one doesn’t work. Senior developers aren’t just copying/pasting – they read the methods carefully & apply them wisely to each case.

Method 1

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

Method 2

You’re looking for: get_attachment_link( $attachment->ID ).


As toscho suggested in his comment, you can also use the generic get_permalink() function which internally calls get_attachment_link().

Method 3

Great! changing the lines

'post_mime_type'=>'image', 
  echo wp_get_attachment_link( $attachment-  >ID, '' , true, false, 'Link to image attachment' );

to

 'post_mime_type'=>'application', 
  echo wp_get_attachment_link( $attachment->ID, '' , false, false, 'Download File' );

I could link a direct download from PDF File attached to post

Method 4

I was looking for the code that can able to pull exact URL of corresponding image from media and found this thread. I tweaked it little bit

Here is the code that I used to pull image for PIN IT button…..

<?php

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_url( $attachment->ID ) . '';
}

?>


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Comment