Need a Website?

How to Set Cookies When Using a WordPress Caching Plugin (Without Clearing Cache)

If you have ever tried setting a cookie in WordPress and found that it only appears after clearing your cache, you are not alone. This is one of the most common issues developers face when using caching plugins such as WP Rocket, LiteSpeed Cache, W3 Total Cache, SiteGround Optimizer, or Breeze.

In this article, you will learn why your cookie does not show up and how to fix it without disabling your caching plugin.

Why Cookies Do Not Work on Cached Pages

Caching plugins speed up your WordPress site by generating and serving static HTML files to visitors. This means most PHP code, including functions like setcookie() or conditional logic in functions.php, does not run on every request.

For example, you might have something like this:

if (isset($_GET['ref'])) {
  setcookie('ref', $_GET['ref'], time() + 3600, '/');
}

This will work the first time before the page is cached. After that, your visitors will receive a pre-built static version of the page, and PHP will not execute again until you clear the cache. That is why the cookie seems to appear only after a cache purge.

The Correct Way to Set Cookies Without Clearing Cache

To keep your site fast and still set cookies dynamically, you need to move that logic outside the cache layer.

Here are three effective methods you can use.

This is the easiest and most cache-safe method.

Add the following script in your site footer (for example, inside footer.php or using a custom JavaScript plugin):

<script>
document.addEventListener("DOMContentLoaded", function() {
  const params = new URLSearchParams(window.location.search);
  const ref = params.get('ref'); // change 'ref' to your URL parameter name

  if (ref) {
    document.cookie = "ref=" + encodeURIComponent(ref) + "; path=/; max-age=" + (60 * 60 * 24 * 30);
  }
});
</script>

Why it works:

  • It runs in the browser, so it is not affected by server-side caching.
  • It works instantly on any cached page.
  • It does not require clearing cache or disabling performance plugins.

Optional: To remove the URL parameter after setting the cookie, you can add this:

if (ref) {
  const newUrl = window.location.pathname + window.location.hash;
  window.history.replaceState({}, document.title, newUrl);
}

This keeps your links clean for SEO and sharing.

2. Set Cookies Using AJAX or REST API

If you need to handle cookies from the server side, for example to log or validate the data, you can use AJAX. AJAX endpoints are not cached by WordPress, so this method will always work.

JavaScript:

const params = new URLSearchParams(window.location.search);
const ref = params.get('ref');

if (ref) {
  fetch('/wp-admin/admin-ajax.php?action=set_ref_cookie&ref=' + encodeURIComponent(ref));
}

PHP (functions.php):

add_action('wp_ajax_nopriv_set_ref_cookie', 'set_ref_cookie');
add_action('wp_ajax_set_ref_cookie', 'set_ref_cookie');

function set_ref_cookie() {
  if (!empty($_GET['ref'])) {
    setcookie('ref', sanitize_text_field($_GET['ref']), time() + 3600 * 24 * 30, '/');
  }
  wp_die();
}

Why it works:
AJAX and REST API routes are never cached, so the PHP code runs every time.

3. Exclude Certain Pages or Cookies From Cache

If your cookie logic must always run before the page loads, you can exclude specific pages or cookies from caching.

Most caching plugins include settings like:

  • Never Cache These URLs
  • Exclude Cookies
  • Disable Cache for Logged-In Users

Use these settings to prevent caching on the specific pages that need real-time PHP execution.

Bonus: Store Multiple URL Parameters as Cookies

If your marketing URLs include several tracking parameters, such as:

https://example.com/?ref=123&utm_source=google&utm_campaign=winter-sale

You can store all of them automatically as cookies using this script:

<script>
document.addEventListener("DOMContentLoaded", function() {
  const params = new URLSearchParams(window.location.search);
  params.forEach((value, key) => {
    document.cookie = key + "=" + encodeURIComponent(value) + "; path=/; max-age=" + (60 * 60 * 24 * 30);
  });
});
</script>

Now every parameter (for example ref, utm_source, utm_campaign) will be saved as its own cookie and can later be accessed in PHP with $_COOKIE.

Comparison Table

MethodWorks With CacheDifficultyBest For
JavaScriptYesEasyTracking, marketing, referrals
AJAX or REST APIYesMediumServer-side logic, validation
Cache ExclusionPartialMediumWooCommerce, login, membership pages

Conclusion

Caching plugins are excellent for improving site performance, but they also change how and when PHP executes. This can break functions like setcookie() if you rely only on backend logic.

The good news is you do not need to disable or clear your cache to make cookies work. By setting cookies through JavaScript or using non-cached endpoints such as AJAX, you can keep your website both fast and fully functional.

Picture of Wayan

Wayan

I am a web developer with over 7 years of experience, WordPress is my mainstay. I build responsive, attractive websites, as well as optimize performance and security. In addition, I also enjoy sharing the knowledge I gained from my experience through this blog. Hopefully, the information I share will be useful to you readers. Thank you for visiting my blog!

I start by understanding your need

I also available on Whatsapp