REST API & Developer PHP Intermediate

Let Browsers and CDNs Cache Public REST Responses

Add Cache-Control headers to public, logged-out REST API GET requests, so headless sites and CDNs can cache them for a few minutes.

Tested on WordPress 7.1 PHP 8.3 No plugin needed Updated
functions.php 16 lines
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 );

Where to add this

Recommended A code snippets plugin Survives theme changes and is easy to switch off.
Child theme At the end of your child theme's functions.php file.
Must-use plugin As a .php file in wp-content/mu-plugins, starting with <?php.

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.

How it works

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.

Things to watch

  • Logged-in requests and anything that isn’t GET are never cached.
  • Changes to posts can take up to five minutes to appear through the API. Lower max-age if that matters.
  • Some hosts and CDNs ignore or override this header. Check their caching rules.

How to test it

Run curl -I https://yoursite.com/wp-json/wp/v2/posts. You should see Cache-Control: public, max-age=300.

This website uses cookies to enhance your browsing experience and ensure the site functions properly. By continuing to use this site, you acknowledge and accept our use of cookies.

Accept All Accept Required Only