wp code snippet

WordPress, PHP quick help codes

How to force PDF to download in WordPress?

Before starting I assume that you already create custom field i.e. “_pdf_download_link” for PDF field.

<a href="<?php the_permalink(); ?>/?download=<?php echo $post->ID ?>">Download PDF</a>

At the beginning of the template theme file, before get_header() place below code.

if(isset($_GET['downlaod']) && (int)$_GET['downlaod']>0) {
 $id = (int)$_GET['downlaod'];
 $file = get_post_meta($id, '_pdf_download_link', true);
 $pdf = basename($file);
 $base = $_SERVER['DOCUMENT_ROOT'].'/wp-content/uploads/';
 header('Content-type: application/pdf');
 header('Content-disposition: attachment; filename='.$pdf);
 header("Pragma: no-cache");
 header("Expires: 0");

Categories: PHP, WordPress

Leave a Reply

%d bloggers like this: