Is there a dedicated WP function, action or filter to use when adding/modifying the HTTP headers?
For now I just hook a PHP header() call into the WP ‘init’ hook like this:
add_action('init', 'add_header_xua');
function add_header_xua(){
if(!is_admin()){
header('X-UA-Compatible: IE=edge,chrome=1');
}
}
But is this the correct way to do that?
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
The init action is the wrong place to do it. A better place would be at template_redirect, so that you only affect the front end view of the site and not the admin areas.
Method 2
Here is the code I’ve used, based on the original question and on Dominic P’s answer…
/*
* Modify HTTP header
*/
function add_header_xua($headers) {
// var_dump($headers); #=> if you want to see the current headers...
if (!is_admin()) {
$headers['X-UA-Compatible'] = 'IE=edge,chrome=1';
}
return $headers;
}
add_filter('wp_headers', 'add_header_xua');
Once you’ve added that code to your functions.php file, you can check it works by running a test at http://web-sniffer.net/ to ensure the HTTP headers have indeed changed.
Method 3
I know it’s been a while, but if anyone else stumbles on this, I found a WordPress hook specifically for modifying HTTP headers. The hook is wp_headers and it’s called in the wp class.
The first argument passed is an array of headers with the header name as the key. The second argument is a reference to the wp class object.
Method 4
send_headers is the preferred method over wp_headers for this situation as demonstrated in the codex.
is_admin() || add_action('send_headers', function(){
header('X-UA-Compatible: IE=edge,chrome=1');
}, 1);
Here’s my explanation for why on a similar question.
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0