nocache_headers()
云策文档标注
概述
nocache_headers() 函数用于设置 HTTP 头部,以阻止不同浏览器的缓存行为。它通过发送多个头部来确保所有浏览器都能正确识别不应缓存内容。
关键要点
- 函数发送多种 HTTP 头部以防止浏览器缓存,兼容不同浏览器。
- 内部调用 wp_get_nocache_headers() 获取头部信息,并移除 Last-Modified 头部。
- 如果头部已发送,函数会提前返回,避免错误。
- 常用于需要禁用缓存的场景,如错误处理、登录验证或自定义管理页面。
代码示例
add_filter( 'nocache_headers', function() {
return array(
'Cache-Control' => 'no-store, no-cache, must-revalidate, max-age=0, some-custom-thing',
'Pragma' => 'no-cache',
'Expires' => gmdate( 'D, d M Y H:i:s \G\M\T', time() )
);
} );注意事项
- 函数在 WordPress 2.0.0 版本引入,使用时需确保头部未提前发送。
- 可通过 nocache_headers 过滤器自定义头部,如示例中所示。
原文内容
Sets the HTTP headers to prevent caching for the different browsers.
Description
Different browsers support different nocache headers, so several headers must be sent so that all of them get the point that no caching should occur.
See also
Source
function nocache_headers() {
if ( headers_sent() ) {
return;
}
$headers = wp_get_nocache_headers();
unset( $headers['Last-Modified'] );
header_remove( 'Last-Modified' );
foreach ( $headers as $name => $field_value ) {
header( "{$name}: {$field_value}" );
}
}
Changelog
| Version | Description |
|---|---|
| 2.0.0 | Introduced. |
Skip to note 2 content
iSaumya
Use nocache_headers to add custom headers to
wp-adminpages. Example code:add_filter( 'nocache_headers', function() { return array( 'Cache-Control' => 'no-store, no-cache, must-revalidate, max-age=0, some-custom-thing', 'Pragma' => 'no-cache', 'Expires' => gmdate( 'D, d M Y H:i:s GMT', time() ) ); } );