0

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.

1

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

  • Thanks for pointing @Krzysiek but I tried in many ways that function and somehow it doesn't work on the home template. – Rico Letterman Sep 25 '15 at 13:51
  • @audaz802 Wellness, it works, because WordPress uses it in many places. Can you show your code? How did you use it? – Krzysiek Dróżdż Sep 25 '15 at 15:09
  • Sure, I updated my question. – Rico Letterman Sep 25 '15 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... – Krzysiek Dróżdż Sep 27 '15 at 8:14
0
 $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, privacy policy and cookie policy

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