Add Cache-Control headers to public, logged-out REST API GET requests, so headless sites and CDNs can cache them for a few minutes.
add_filter( 'rest_post_dispatch', function ( WP_REST_Response $response, WP_REST_Server $server, WP_REST_Request $request ): WP_REST_Response {
if ( 'GET' !== $request->get_method() || is_user_logged_in() || $response->is_error() ) {
return $response;
}
$cacheable = [ '/wp/v2/posts', '/wp/v2/pages', '/wp/v2/categories', '/wp/v2/tags' ];
foreach ( $cacheable as $prefix ) {
if ( str_starts_with( $request->get_route(), $prefix ) ) {
$response->header( 'Cache-Control', 'public, max-age=300, stale-while-revalidate=60' );
break;
}
}
return $response;
}, 10, 3 );
Always add PHP to a staging site first, or have FTP or file manager access ready, so you can undo it if something goes wrong.
REST API responses aren’t cached by browsers or CDNs by default, so every request runs WordPress in full. For headless sites that read the same posts again and again, a short cache time takes a lot of load off the server.
rest_post_dispatch runs after a REST request has been handled, before the response is sent. For successful GET requests from visitors who aren’t logged in, the snippet adds a Cache-Control header to the routes in your list.
max-age=300 allows caching for five minutes. stale-while-revalidate lets a cache serve the old copy for another minute while it fetches a new one.
max-age if that matters.Run curl -I https://yoursite.com/wp-json/wp/v2/posts. You should see Cache-Control: public, max-age=300.