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

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

Tags:

Leave a Reply

Your email address will not be published. Required fields are marked *