5

In WordPress, how do I create a link to a file such as "file.pdf" and force it to download instead of opening the file in the browser?

Community
  • 1
  • 1
rowmoin
  • 698
  • 2
  • 8
  • 17

2 Answers2

9

Just add download attribute ( download) on your a tags and leave it empty as a default file name of a file.

Example: < a href="http://wordpress.org/download/download.pdf" target="_blank" download>WordPress Download PDF</a>

rowmoin
  • 698
  • 2
  • 8
  • 17
  • 1
    This will work only in some browser. Safari is not one of them! – Jorge L Hernandez Nov 30 '17 at 21:02
  • It's problem on safari browser for anchor tag so you can see that link :://stackoverflow.com/questions/22643032/anchor-tag-doesnt-work-in-iphone-safari – rowmoin Dec 01 '17 at 16:19
  • 1
    I needed this in my Wordpress site and it worked perfectly! Thank you! – jord8on Dec 13 '18 at 20:12
  • 1
    Thanks a lot jord8on. I am feeling good to heard that solution help you. – rowmoin Dec 19 '18 at 15:04
  • it helped me to force the download of a fillable pdf form that didn't work on the pdf viewer of some browsers. Now it auto download so people open it with adobe or else. – Simon the Salmon Jan 16 '19 at 09:36
  • Am really happy to heard that @Simon the Salmon – rowmoin Jan 18 '19 at 12:22
  • Just coming back to further clarify... The answer provided by @rowmoin works IF THE FILE is hosted on your wordpress instance AND you are using Chrome or Firefox. I tried to force download a file that was not hosted on my wordpress installation and it did not work. So I uploaded the file to my site and then used the URL from my site (as prescribed in rowmoin's answer) and then when I clicked the link, the download initiatied instantly. My experience was using the latest version of Google Chrome. I tested Firefox and it worked. I tested Safari and it did not work. – jord8on Feb 02 '19 at 23:47
  • Upvote the @vijay kanaujia response – Pedro Apr 19 '22 at 16:02
4

make download.php in theme folder

<?php
    
    $url = $_REQUEST['file_url'];
    $filename = basename($url);
    $filetype = filetype($url);
    header('Content-Disposition: attachment; filename=' . $filename);
    header("Content-type: " . $filetype); // act as image with right MIME type
    ob_clean();
    flush();
    readfile($url);
    exit;

then hit anchor link from html page. in this code your file url may be same domain or diffrent domain does not matter

<a href="https:://domain.com/wp-content/themes/gallerywp/download.php?file_url=fileurl" target="_blank">click to download</a>
Vijay Kanaujia
  • 439
  • 4
  • 9
  • The easy way in 2022 while last versions of Chrome/FF are not supporting the 'download' attribute. – Pedro Apr 19 '22 at 16:02