Performance PHP Intermediate

Add Cache Headers for Logged-Out Visitors

Let your CDN and browsers cache public pages for a few minutes, while keeping logged-in users, carts and checkout uncached.

Tested on WordPress 7.1 PHP 8.3 No plugin needed Updated
functions.php 19 lines
add_action( 'template_redirect', function (): void {
	if ( is_user_logged_in() || 'GET' !== $_SERVER['REQUEST_METHOD'] || is_search() || is_404() || post_password_required() ) {
		return;
	}

	// Never cache WooCommerce cart, checkout or account pages.
	if ( function_exists( 'is_cart' ) && ( is_cart() || is_checkout() || is_account_page() ) ) {
		return;
	}

	// Visitors who commented see their own pending comments.
	foreach ( array_keys( $_COOKIE ) as $name ) {
		if ( str_starts_with( $name, 'comment_author_' ) || str_starts_with( $name, 'woocommerce_items_in_cart' ) ) {
			return;
		}
	}

	header( 'Cache-Control: public, max-age=300, s-maxage=600' );
}, 99 );

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.

WordPress doesn’t send cache headers for normal pages, so CDNs like Cloudflare or Bunny.net either don’t cache HTML or need rules set up by hand. This snippet tells caches a page is safe to store for a few minutes, and only for visitors who see the same page as everyone else.

How it works

On template_redirect, after WordPress knows what page it’s showing, the snippet skips logged-in users, form posts, searches, 404s, password-protected posts, WooCommerce’s cart, checkout and account pages, and visitors with a comment or cart cookie.

Everyone else gets Cache-Control: public, max-age=300, s-maxage=600: browsers may reuse the page for 5 minutes and shared caches like your CDN for 10.

Things to watch

  • Your CDN decides whether to honour these headers. Bunny.net and Cloudflare (with a “Cache Everything” rule set to respect origin headers) do.
  • If you already use a caching plugin, it probably sends its own headers. Don’t use both.
  • Content changes can take up to 10 minutes to show for visitors. Purge your CDN after important updates.

How to test it

In a private window, check a post’s response headers in DevTools. You should see the Cache-Control header. Logged in, it shouldn’t be there.

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