如何禁用WordPress REST API缓存?开发调试遇缓存延迟问题
禁用WordPress REST API缓存的解决方案
问题根源
你的回调函数直接用echo json_encode($response); die();输出内容,没有遵循WordPress REST API的规范返回响应对象,导致无法正确设置缓存控制头,进而被服务器、CDN或浏览器缓存了旧响应。
解决方法
方法1:使用WP规范响应对象并设置缓存头
修改回调函数,返回WP_REST_Response对象,同时添加缓存控制头禁用所有缓存:
function get_wp_page_callback2( $request) { $response_data = [ "response" => 'test', "url" => 33, ]; $response = new WP_REST_Response($response_data); // 设置缓存控制头,禁止各类缓存 $response->set_headers([ 'Cache-Control' => 'no-cache, no-store, must-revalidate', 'Pragma' => 'no-cache', 'Expires' => '0' ]); return $response; }
方法2:全局临时禁用REST API缓存(仅调试用)
如果需要在调试阶段全局禁用REST API缓存,可将以下代码添加到主题的functions.php中:
add_filter('rest_post_dispatch', 'disable_rest_api_cache', 10, 3); function disable_rest_api_cache($response, $server, $request) { // 仅在WP_DEBUG模式下生效,避免影响生产环境 if (defined('WP_DEBUG') && WP_DEBUG) { $response->set_headers([ 'Cache-Control' => 'no-cache, no-store, must-revalidate', 'Pragma' => 'no-cache', 'Expires' => '0' ]); } return $response; }
方法3:排查外部缓存因素
如果上述方法无效,检查是否存在外部缓存机制:
- 检查CDN服务(如Cloudflare)是否开启了页面缓存,临时禁用CDN或把你的API路径
/wp/v2/tf_api/get_wp_page2加入缓存排除列表 - 检查服务器端缓存(如Nginx、Apache缓存规则)或WordPress缓存插件(如WP Rocket),将API路径添加到缓存排除规则里
注意事项
- 调试完成后,建议恢复合理的缓存策略,避免影响生产环境性能
- 开发REST API时尽量遵循官方规范,使用
WP_REST_Response类处理输出,避免直接用echo和die
内容的提问来源于stack exchange,提问作者Aclua
相关产品推荐
相关产品推荐

