Skip to content

Adding and Removing Cookies

Donncha Ó Caoimh edited this page Oct 17, 2020 · 1 revision

Introduction

Cached pages are either:

  • Anonymous, where the visitor has no cookies set in their browser
  • Known, where the visitor has a cookie set by something like a cookie banner or shopping cart.

Anonymous pages are served to everyone who have no cookie set which will probably be the majority of your visitors but if you have a cookie banner, shopping cart or some other personalisation on your site they may stop working correctly until you tell WP Super Cache about the cookies they use. WP Super Cache only uses the default WordPress cookies by default. These are usually login and comment cookies, but it is possible to add other cookie names to the cookie list used as a key to identify cached pages.

Actions

The plugin has two actions that will allow you to modify the cookie list:

  • wpsc_add_cookie
  • wpsc_delete_cookie

If your plugin sets a cookie to personalise a page you should fire the wpsc_add_cookie action with that cookie name as the argument. The cookie name will be added to the list of cookies used by the plugin. You do not need to fire it on every request as the cookie name is saved in the WP Super Cache configuration but if you do, the list won't be updated, so there's little harm in doing so.

do_action( 'wpsc_add_cookie', 'plugin_cookie_name' );

To delete a cookie use the wpsc_delete_cookie action in the same way. Fire it once and the cookie will be removed.

do_action( 'wpsc_delete_cookie', 'plugin_cookie_name' );

By using an action your plugin will simply work out of the box if WP Super Cache is installed, but if it is not present, the action will do nothing.

Example

I have a cookie banner plugin that sets a cookie called "eucookie" when a visitor clicks the confirmation button. If I do nothing the cookie banner will still be displayed after I click the confirmation button because the page will be cached. Anywhere in the cookie banner plugin I will add the following line of code:

do_action( 'wpsc_add_cookie', 'eucookie' );

I clear the cache in WP Super Cache and reload my page, click the confirmation button, and the banner will disappear.

To clean up after me, I add the following line of code to the deactivate function in my cookie banner plugin:

do_action( 'wpsc_delete_cookie', 'eucookie' );

CAVAET

Modifying the cookie list will not be enough in all circumstances. If you have a rating plugin that uses PHP to display the rating the page will show a stale rating to visitors who have not voted yet as their browser will not have the rating cookie. In this case you must enable dynamic caching in the plugin and create a dynamic caching helper plugin. It is not simple to do so however. An example plugin is here. It is probably better to use an AJAX request to fetch the rating.

If you are looking for a rating plugin that does work on cached pages I can recommend the Crowdsignal plugin.