如何在页面模板中创建文件下载链接

时间:2016-02-08 11:39:00

标签: php wordpress download

我需要在word press中点击链接下载文件。 我有文件网址。 我知道php中的下载代码,我在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);
}

现在如何点击链接调用此功能?什么是" href"的链接

2 个答案:

答案 0 :(得分:3)

在包含链接的页面上:

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

download.php上(或您选择的任何名称):

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

修改或只创建一个download.php页面:

<?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;
?>

答案 1 :(得分:0)

您可以做的是在Wordpress后端创建一个新的页面,并将您的php标题放在该页面的自定义模板中,而不是创建一个函数(简单的pdf下载) :

<?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);
?>

然后你可以简单地将永久链接放到新的wordpress页面作为下载链接上的href。 wordpress页面的永久链接可以在wordpress后端随意编辑,所以你可以这样做:

www.example.com/downloadfile

我知道它已经老了,但我最近也遇到了这个问题,希望它能帮助那些在这里结束的人!

相关问题