wp_headers
Allows you to change HTTP headers before they are sent to the browser.
Usage
add_filter( 'wp_headers', 'wp_kama_headers_filter', 10, 2 );
/**
* Function for `wp_headers` filter-hook.
*
* @param string[] $headers Associative array of headers to be sent.
* @param WP $wp Current WordPress environment instance.
*
* @return string[]
*/
function wp_kama_headers_filter( $headers, $wp ){
// filter...
return $headers;
}
Examples
#1 Headers passed through the filter
Add the following code to functions.php and visit the site's home page:
add_filter( 'wp_headers', 'wp_kama_headers_filter_test', 10, 2 )
function wp_kama_headers_filter_test( $headers, $wp ){
error_log( print_r( $headers, true ) );
return $headers;
}
The debug log will contain the following.
Logged-in user:
Array ( [Expires] => Wed, 11 Jan 1984 05:00:00 GMT [Cache-Control] => no-cache, must-revalidate, max-age=0 [Last-Modified] => [Content-Type] => text/html; charset=UTF-8 )
Guest:
Array ( [Content-Type] => text/html; charset=UTF-8 )
#2 Prevent site indexing during development
Developers often demonstrate work on a DEV version of a site. To prevent this duplicate site from being indexed, use the following code to tell search engines “do not index me”:
if ( 'development' === wp_get_environment_type() ){
add_filter( 'wp_headers', 'disable_indexing_site' );
/**
* Prevents site indexing during development.
*/
function disable_indexing_site( $headers ) {
$headers['X-Robots-Tag'] = 'noindex, nofollow';
return $headers;
}
}
See also: Prevent search engines from indexing a DEV version of a site.
Changelog
| Since 2.8.0 | Introduced. |
Where the hook is called
wp_headers
wp-includes/class-wp.php 563
$headers = apply_filters( 'wp_headers', $headers, $this );
Where the hook is used in WordPress
wp-includes/class-wp-customize-manager.php 1923
add_filter( 'wp_headers', array( $this, 'filter_iframe_security_headers' ) );