Get the attachment URL on single.php

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!

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

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

0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments