Preload custom cookie

In some cases, you might want to preload the cache for specific values of a dynamic cookie instead of the regular cache version.

Note that preload will skip preload all variants if cache is already generated with a user visit.

To achieve it, you can use the following helper plugin:

๐Ÿ“ฅ   Download (.zip):  WP Rocket | Preload Dynamic Cookie Values
Developers: You can find the code for this plugin on GitHub.

๐Ÿ“ Manual code edit required before use!

  1. After downloading the plugin zip file, unzip it and open the PHP file in a text editor.
  2. Edit the cookie name and values you want to preload on lines 49 - 53
  3. If you want to preload the values of two different cookies, you can uncomment the 2nd set in the helper (lang in the example):
    $cookies = [
    	'currency' => [
    		'usd',
    		'eur',
    	],
    	'lang' => [
    		'en',
    		'es',
    	], 
    ];
    	

    The example above will preload two cookies:

    Cookie 1: currency with values usd and eur
    Cookie 2: lang with values en and es

  4. After making your edits, save the PHP file and re-zip the plugin. 
  5. In your WordPress site, go to Plugins > Add New > Upload Plugin and upload the zip file. 
  6. Activate it and then clear the WP Rocket cache.

In that case, if a user visit generates a page with currency=usd & lang=en before preload, preload will skip all other variants.

Preload a single cookie value

Another option, to preload a single cookie value,  is to customize the following code snippet. Replace any instances of  cookie_name and cookie_value with the name and the value of the cookie you would like to preload.

function custom_cookie_preload( $args ) {
	$cookie = new WP_Http_Cookie( 'cookie_name' );
	$cookie->name = 'cookie_name';
	$cookie->value = 'cookie_value';
	$cookies[] = $cookie;
	
	$args['cookies'] = $cookies;
	
	return $args;
}
add_filter( 'rocket_preload_url_request_args', 'custom_cookie_preload', PHP_INT_MAX );

You need to add the customized code to the  functions.php of your child theme or use a code snippets plugin.
Reference: How to add code snippets.

Did this answer your question? Thanks for the feedback There was a problem submitting your feedback. Please try again later.