Skip Page Caching for Visitors With a Cookie
Makes page-cache plugins (WP Rocket, W3 Total Cache, WP Super Cache, LiteSpeed Cache and others that respect DONOTCACHEPAGE) skip caching for visitors who carry a cookie you choose, such as a personalisation, A/B test or affiliate cookie.
Opens WPIDE on
Code
$wpide_cookie = 'wpide_variant'; // Cookie name (prefix match).
add_filter( 'rocket_cache_reject_cookies', function ( $cookies ) use ( $wpide_cookie ) {
$cookies = (array) $cookies;
$cookies[] = $wpide_cookie;
return array_values( array_unique( $cookies ) );
} );
add_action( 'init', function () use ( $wpide_cookie ) {
if ( is_admin() || empty( $_COOKIE ) ) {
return;
}
foreach ( array_keys( $_COOKIE ) as $name ) {
if ( 0 === strpos( (string) $name, $wpide_cookie ) ) {
if ( ! defined( 'DONOTCACHEPAGE' ) ) {
define( 'DONOTCACHEPAGE', true );
}
if ( defined( 'LSCWP_V' ) ) {
do_action( 'litespeed_control_set_nocache', 'wpide cookie' );
}
break;
}
}
}, 1 );
Notes
Set $wpide_cookie. WP Rocket also gets the cookie added to its "never cache" list, so cached copies are not served to those visitors; re-save its settings once.
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.