2

I'm building a theme that generates on the home template a link to the PDF attached to the post (it will be only PDF files).

I found a solution to check if the post has a PDF attached. The goal is to create a link that downloads the file, on the home (blog) template.

Here's what I currently have

function leoni_get_attachment() {
    global $post; 
    $args = array(
        'post_type'      => 'attachment',
        'post_mime_type' => 'application/pdf',
        'post_parent'    => $post->ID,
    );

    $attachments     = get_posts($args);
    $attachment_link = wp_get_attachment_url();

    if ($attachments) {
        echo '<a href="'. $attachment_link .'">Download</a>';
    } else {
    return false;
    }
}

I've tried using get_attached_file() without success.

2 Answers 2

7

Well, there is a WP function for that.

wp_get_attachment_url

It takes attachment id as argument, so you can use it like in following example:

echo wp_get_attachment_url( 12 );

This will echo url to attachment which id is 12.

You can find more info and examples on Codex page: https://codex.wordpress.org/Function_Reference/wp_get_attachment_url

4
  • Thanks for pointing @Krzysiek but I tried in many ways that function and somehow it doesn't work on the home template. Commented Sep 25, 2015 at 13:51
  • @audaz802 Wellness, it works, because WordPress uses it in many places. Can you show your code? How did you use it? Commented Sep 25, 2015 at 15:09
  • Sure, I updated my question. Commented Sep 25, 2015 at 21:36
  • 2
    OK. But you have to pass attachment ID as param for this function to work. How should it know which attachment's url to return? And second thing... get_posts returns array of posts, not one of them. So you'll need some loop in your code... Commented Sep 27, 2015 at 8:14
1
 $attachment_link = wp_get_attachment_url( $attachments[0]->ID );

Try replacing your link with, this one. You need to pass an argument to get the url which is the attachment ID.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.