add http header to wordpress

六月ゝ 毕业季﹏ 提交于 2020-05-12 07:11:42

问题


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

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

how can i do this with wordpress?

heres the code with the headers

$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);
}

回答1:


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

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




回答2:


You need to use a hook that executes before Wordpress adds anything to the output. One such hook is "init"

function do_my_stuff_with_headers() {
    // ...
}
add_action( 'init', 'do_my_stuff_with_header' );


来源:https://stackoverflow.com/questions/13517548/add-http-header-to-wordpress

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!