wp_headers
云策文档标注
概述
wp_headers 是一个 WordPress 过滤器,用于在 HTTP 头部发送到浏览器之前进行修改。它允许开发者自定义响应头,但需注意缓存系统可能影响其效果。
关键要点
- wp_headers 过滤器接收一个关联数组 $headers 作为参数,用于修改 HTTP 头部。
- 此过滤器在 WP::send_headers() 方法中被调用,用于发送缓存、内容类型等额外头部。
- 如果站点使用插件或第三方缓存系统,wp_headers 可能无法修改已缓存的页面头部,因为缓存页面会在过滤器执行前被提供。
- 作为替代方案,可以通过 wp_head() 添加 HTML meta 标签(使用 http-equiv 属性)或在服务器级别(如 .htaccess)设置头部。
代码示例
function gnu_terry_pratchett_meta() {
if ( WP_CACHE ) {
echo '<meta http-equiv="X-Clacks-Overhead" content="GNU Terry Pratchett">';
}
}
add_action( 'wp_head', 'gnu_terry_pratchett_meta' );注意事项
在缓存环境中使用 wp_headers 过滤器时,需考虑其局限性,并探索其他方法如服务器配置来确保头部正确设置。
原文内容
Filters the HTTP headers before they’re sent to the browser.
Parameters
$headersstring[]-
Associative array of headers to be sent.
$wpWP-
Current WordPress environment instance.
Source
$headers = apply_filters( 'wp_headers', $headers, $this );
Changelog
| Version | Description |
|---|---|
| 2.8.0 | Introduced. |
Skip to note 2 content
Nick C
This filter won’t allow you to modify headers if your site serves cached pages via a plugin or third-party caching system. The cached page will be served before your wp_headers are filtered.
You may be able to add an HTML meta tag with the http-equiv attribute using wp_head() to work around this for certain headers: http://reference.sitepoint.com/html/meta/http-equiv
function gnu_terry_pratchett_meta() { if ( WP_CACHE ) { echo '<meta http-equiv="X-Clacks-Overhead" content="GNU Terry Pratchett" />'; } } add_action( 'wp_head', 'gnu_terry_pratchett_meta' );Alternatively, explore setting headers at the server level with .htaccess or similar if you can.
header set X-Clacks-Overhead "GNU Terry Pratchett"