WordPress – How to use the PHP header() function

I need to use PHP headers like header( 'Location: http://location.com' ); or header("Content-disposition: attachment; filename=$fileName"); from my wordpress plugin but it won’t seem to how. I know that they need to be used before the page header is called, so I tried using the init hook:

add_action('init', 'test');

function test() {
    header( 'Location: http://location.com' ) ;
}

but it didn’t work.

Related posts

Leave a Reply

1 comment

  1. If you want to redirect any page then use wp_redirect() method.. OR if you want to set the specific headers to make the content downloadable.. use below sample..code…

    Suppose your url is like.. http://example.com/download/data.csv

    add_action('template_redirect','yoursite_template_redirect');
    function yoursite_template_redirect() {
        if ($_SERVER['REQUEST_URI']=='/downloads/data.csv') {
            header("Content-type: application/x-msdownload",true,200);
            header("Content-Disposition: attachment; filename=data.csv");
            header("Pragma: no-cache");
            header("Expires: 0");
            echo 'data';
            exit();
        }
    }