将http标头添加到wordpress [英] add http header to wordpress

查看:145
本文介绍了将http标头添加到wordpress的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

i'm trying to build custom zip files on demand and have found some code that seems to work fine http://www.9lessons.info/2012/06/creating-zip-file-with-php.html

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

i've inserted the code in my wordpress template and the only thing is that the header()

必须在模板加载之前发送

have to be sent before the template is loaded

我如何用wordpress做到这一点?

how can i do this with 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);
}

推荐答案

Wordpress为此有一个钩子.通过调用add_action函数将标头添加到send_headers挂钩.

Wordpress has a hook for this. Add the headers to the send_headers hook by calling the add_action function.

$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文件中的功能

This will all need to go in a function in your functions.php file in your theme folder

这篇关于将http标头添加到wordpress的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆