函数文档

wp_get_nocache_headers()

💡 云策文档标注

概述

wp_get_nocache_headers() 函数用于获取防止缓存的 HTTP 头信息数组,适用于 WordPress 开发中控制浏览器或代理服务器缓存行为。

关键要点

  • 返回关联数组,包含 Expires、Cache-Control 等头字段,默认设置如 no-cache、must-revalidate 等。
  • 可通过 apply_filters('nocache_headers', $headers) Hook 过滤头信息,允许自定义缓存控制策略。
  • 函数内部设置 Last-Modified 为 false,并支持版本更新(如 6.8.0 添加 no-store 和 private 指令)。

代码示例

function wp_get_nocache_headers() {
    $cache_control = 'no-cache, must-revalidate, max-age=0, no-store, private';
    $headers = array(
        'Expires'       => 'Wed, 11 Jan 1984 05:00:00 GMT',
        'Cache-Control' => $cache_control,
    );
    if ( function_exists( 'apply_filters' ) ) {
        $headers = (array) apply_filters( 'nocache_headers', $headers );
    }
    $headers['Last-Modified'] = false;
    return $headers;
}

注意事项

该函数常用于 REST API 请求处理或发送 HTTP 头时,确保内容不被缓存,开发者应结合 WP_REST_Server 或 WP 类使用。


📄 原文内容

Gets the HTTP header information to prevent caching.

Description

The several different headers cover the different ways cache prevention is handled by different browsers or intermediate caches such as proxy servers.

Return

array The associative array of header names and field values.

Source

function wp_get_nocache_headers() {
	$cache_control = 'no-cache, must-revalidate, max-age=0, no-store, private';

	$headers = array(
		'Expires'       => 'Wed, 11 Jan 1984 05:00:00 GMT',
		'Cache-Control' => $cache_control,
	);

	if ( function_exists( 'apply_filters' ) ) {
		/**
		 * Filters the cache-controlling HTTP headers that are used to prevent caching.
		 *
		 * @since 2.8.0
		 *
		 * @see wp_get_nocache_headers()
		 *
		 * @param array $headers Header names and field values.
		 */
		$headers = (array) apply_filters( 'nocache_headers', $headers );
	}
	$headers['Last-Modified'] = false;
	return $headers;
}

Hooks

apply_filters( ‘nocache_headers’, array $headers )

Filters the cache-controlling HTTP headers that are used to prevent caching.

Changelog

Version Description
6.8.0 The Cache-Control header now includes the no-store and private directives regardless of whether a user is logged in.
6.3.0 The Cache-Control header for logged in users now includes the no-store and private directives.
2.8.0 Introduced.