Let your CDN and browsers cache public pages for a few minutes, while keeping logged-in users, carts and checkout uncached.
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 );
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.
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.
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.