I added a link to a PDF in my custom navigation menu. Is there a way to force it to download instead of open?

  • 1
    right click allows to download. But I believe that is a browser based mechanism, not something on your end Commented May 4, 2011 at 11:06

2 Answers 2


If you don't mind all PDF attachments been forced to be downloaded then you can use something like this:

if (have_posts()) : while (have_posts()) : the_post();

    $pdf_title = $post->post_title;
    $uploads_dir = wp_upload_dir();
    $attachment_src = get_post_meta( $post->ID, '_wp_attached_file', true );
    $pdf_src = path_join( $uploads_dir['basedir'], $attachment_src );
    header("Pragma: public"); // required
    header("Expires: 0");
    header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
    header("Cache-Control: private",false); // required for certain browsers 
    header("Content-Type: application/pdf");
    header("Content-Disposition: attachment; filename=\"".$pdf_title."\";" );
    header("Content-Transfer-Encoding: binary");
    header("Content-Length: ".filesize($pdf_src));

endwhile; endif;

Put the above code in a file called pdf.php in your current theme folder. Then instead of linking direct to your pdf (http://example.com/wp-content/uploads/2011/01/Guide-to-Owning-a-Listed-Building.pdf), link to the attachment URL: (http://example.com/help-and-advice/attachment/guide-to-owning-a-listed-building/)

Doing like the above you can edit the code to do other fancy stuff such as track downloads and add some level of authentication while protecting the actual location of your PDF's.


What happens when the browser encounters a PDF does not depend on how you link to it. You can suggest to the browser that it should download it instead of opening it via a special HTTP header, but I don't think all browsers pay attention to this suggestion.

More information can be found in the Stack Overflow question "Forcing to download a file using PHP".

  • Right on. Or as Dan Tobias said it: “Understand that HTML can't "force" any sort of action, and don't keep trying to get around this limitation; you'll just annoy your users and make your site less accessible.”webtips.dan.info/force.html
    – Geert
    Commented May 4, 2011 at 14:12

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.