Browser and CDN Caching Headers for Visitors
Sends Cache-Control headers on public pages for logged-out visitors, so a CDN or proxy can cache them for a few minutes.
Opens WPIDE on
Code
// Seconds browsers (max-age) and shared caches like CDNs (s-maxage) may reuse a page.
$wpide_browser_cache = 300;
$wpide_cdn_cache = 600;
add_action( 'template_redirect', function () use ( $wpide_browser_cache, $wpide_cdn_cache ) {
if ( headers_sent() || is_user_logged_in() || is_search() || is_404() || is_preview() || post_password_required() ) {
return;
}
if ( 'GET' !== ( isset( $_SERVER['REQUEST_METHOD'] ) ? $_SERVER['REQUEST_METHOD'] : '' ) || ! empty( $_COOKIE['woocommerce_items_in_cart'] ) ) {
return;
}
if ( function_exists( 'is_woocommerce' ) && ( is_cart() || is_checkout() || is_account_page() ) ) {
return;
}
foreach ( array_keys( $_COOKIE ) as $cookie ) {
if ( 0 === strpos( $cookie, 'comment_author_' ) || 0 === strpos( $cookie, 'wp-postpass_' ) ) {
return;
}
}
foreach ( headers_list() as $header ) {
if ( 0 === stripos( $header, 'Cache-Control:' ) ) {
return; // Something else already decided.
}
}
header( sprintf( 'Cache-Control: public, max-age=%d, s-maxage=%d', $wpide_browser_cache, $wpide_cdn_cache ) );
}, 99 );
Notes
Only useful with a CDN or caching proxy in front of the site, and pages with personal content for visitors must be excluded.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.