prasadmsvs
prasadmsvs

Reputation: 1739

How to Create a file download link in a page template

I need to download a file on click of a link in word press. I have file url. I know the download code in php and I added in functions.php.

function downloadFile($f){
    header('Content-Disposition: attachment; filename=' . urlencode($f));
    header('Content-Type: application/force-download');
    header('Content-Type: application/octet-stream');
    header('Content-Type: application/download');
    header('Content-Description: File Transfer');
    header('Content-Length: ' . filesize($f));
    echo file_get_contents($f);
}

Now how to call this function on click of a link? What will be the "href" of the link

Upvotes: 1

Views: 2787

Answers (2)

Paul Botwid
Paul Botwid

Reputation: 1

Instead of creating a function, what you can do is to create a new Page in the Wordpress backend and put your php headers in a custom template for that page, like so (simple pdf download):

<?php
// Specify wordpress template name
/* Template Name: Download Page */

// We'll be outputting a PDF
header('Content-type: application/pdf');

// Set filename of download
header('Content-Disposition: attachment; filename="FILENAME.pdf"');

// Path to the file (searching in wordpress template directory)
$url = get_template_directory_uri() . "/folder/ORIGINAL_FILE.pdf";

readfile($url);
?>

Then you can simply put the permalink to your new wordpress page as the href on the download link. Permalinks for wordpress pages can be edited at will at the wordpress backend, so you could make it something like:

www.example.com/downloadfile

I know it's old but I recently had this problem as well, hope it helps anyone who ended up here as well!

Upvotes: 0

Ben
Ben

Reputation: 9001

On the page with the link:

<a href="download.php?f=foo">Download "Foo"</a>

On download.php (or whatever name you choose):

include "functions.php";
downloadFile($_GET["f"]);
exit;

Edit Or just create a download.php page:

<?php
    if(isset($_GET["f"])){
        $f = $_GET["f"];
        header('Content-Disposition: attachment; filename='.urlencode($f));
        header('Content-Type: application/force-download');
        header('Content-Type: application/octet-stream');
        header('Content-Type: application/download');
        header('Content-Description: File Transfer');
        header('Content-Length: ' . filesize($f));
        echo file_get_contents($f);
    }
    exit;
?>

Upvotes: 3

Related Questions