I added a link to a PDF in my custom navigation menu. Is there a way to force it to download instead of open?
If you don't mind all PDF attachments been forced to be downloaded then you can use something like this:
<?php 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)); ob_clean(); flush(); readfile($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".