3

我正在尝试按需构建自定义 zip 文件,并找到了一些似乎可以正常工作的代码 http://www.9lessons.info/2012/06/creating-zip-file-with-php.html

我已经在我的 wordpress 模板中插入了代码,唯一的事情是header()

必须在加载模板之前发送

我怎么能用wordpress做到这一点?

这是带有标题的代码

$zip = new ZipArchive();            // Load zip library 
$zip_name = time().".zip";          // Zip name
if($zip->open($zip_name, ZIPARCHIVE::CREATE)!==TRUE){       // Opening zip file to load files
    $error .=  "* Sorry ZIP creation failed at this time<br/>";
}
foreach($post['files'] as $file){               
    $zip->addFile($file_folder.$file);          // Adding files into zip
}
$zip->close();
if(file_exists($zip_name)){
    // push to download the zip
    header('Content-type: application/zip');
    header('Content-Disposition: attachment; filename="'.$zip_name.'"');
    readfile($zip_name);
    // remove zip file is exists in temp path
    unlink($zip_name);
}
4

2 回答 2

6

Wordpress 有一个钩子。通过调用函数将标头添加到send_headers钩子中。add_action

$zip = new ZipArchive();
$zip_name = time().".zip";
if($zip->open($zip_name, ZIPARCHIVE::CREATE)!==TRUE){
    $error .=  "* Sorry ZIP creation failed at this time<br/>";
}
foreach($post['files'] as $file) {               
    $zip->addFile($file_folder.$file);
}
$zip->close();
if(file_exists($zip_name)){
    add_action( 'send_headers', 'my_headers' );
    readfile($zip_name);
    // put this somewhere or return it
    // so it can be retrieved later, otherwise
    // it might print before your headers
    // are sent
    unlink($zip_name);
}

function my_headers() {
    header('Content-type: application/zip');
    header('Content-Disposition: attachment;
}

这都需要functions.php在您的主题文件夹中的文件中的一个函数中进行

于 2018-12-14T04:56:13.967 回答
3

您需要使用在 Wordpress 将任何内容添加到输出之前执行的钩子。一个这样的钩子是“init”

function do_my_stuff_with_headers() {
    // ...
}
add_action( 'init', 'do_my_stuff_with_headers' );
于 2012-11-22T22:25:03.443 回答