Create a Lightweight Cookie Notice Plugin for WordPress

December 28, 2020 Posted by Danilo Andreini

Many cookie plugins for WordPress are available on the WordPress.org repository, but it’s hard to find a performance-optimized solution for high-traffic websites.

For this reason, I decided to create a lightweight cookie notice plugin for WordPress and share with you all the details of this implementation.

Ready-to-use plugins available on WordPress.org

I tested the two most popular cookie plugins available on WordPress.org to analyze their possible use in a high-performance website. Here is what I found.

Cookie Notice for GDPR & CCPA is the most popular cookie plugin for WordPress with more than one million downloads.

This plugin loads one CSS file and one JavaScript file in the head section of the page. The jQuery library is not required because the JavaScript file used by the plugin is written in pure JavaScript.

GDPR Cookie Consent is a complete cookie notice plugin. It comes with support for multiple cookie categories, customizable style, shortcodes to improve the cookie policy, and more. In terms of front-end implementation, it adds two CSS files and one JavaScript file. The jQuery library is also required, so you can’t deregister jQuery if this plugin is present.

Create a basic structure for the plugin

We are going to create the following files for the cookie plugin considered in this tutorial:

  • example-cookie-notice.php
  • example-cookie-notice.js
  • example-cookie-notice.css

Add the plugin header comments

Start by adding in the example-cookie-notice.php file the header comments used by WordPress to detect the plugin.

/*
Plugin Name: Example Cookie Notice
Description: Generates a cookie notice on your WordPress website.
Version: 1.00
Author: DAEXT
Author URI: https://daext.com
*/

In the same PHP file add an action associated with the wp_print_footer_script hook. We use this action to print the cookie notice HTML in the page footer.

function print_body_scripts(){

    if(isset($_COOKIE['cookie-accepted'])){
        return;
    }

    ?>

    <div id="cookie-notice">
        <p>Cookies help us provide, protect and improve our products and services. By using our website, you agree to our use of cookies.</p>
        <button id="accept-cookie">Accept</button>
    </div>

    <?php

}
add_action('wp_print_footer_scripts', 'print_body_scripts');

The print_body_script() function above first verifies if the cookie exists. If this cookie doesn’t exist, the function then prints the cookie notice HTML.

As you may notice, our cookie notice is very simple and includes only a container that wraps a paragraph and a button.

Load the plugin resources

Use the wp_enqueue_script hook to load the resources required by the plugin, specifically, the example-cookie-notice.js file and the example-cookie-notice.css file.

function enqueue_scripts(){
    wp_enqueue_style('cookie-notice', plugin_dir_url(__FILE__) . 'example-cookie-plugin.css', array(), null);
    wp_enqueue_script( 'cookie-notice', plugin_dir_url(__FILE__) . 'example-cookie-plugin.js', array(), null, true );
}
add_action('wp_enqueue_scripts', 'enqueue_scripts');

Note that we loaded the JavaScript file in the footer to ensure better loading performance of the page.

Dismiss the notice

In this section, we have to work on the example-cookie-notice.js file. This JavaScript file adds an event listener to detect the click on the button used to dismiss the cookie notice. The callback associated with the event listener performs the following operations:

  • Removes the cookie notice container from the DOM
  • Creates a cookie named cookie-accepted

Here you can find the complete content of this JavaScript file:

window.addEventListener('load', function() {

    let bt = document.getElementById('accept-cookie');
    if(bt){
        bt.addEventListener('click', function(){

            //close the cookie notice
            document.getElementById('cookie-notice').remove();

            //set the cookie
            document.cookie = 'cookie-accepted=1; expires=Thu, 1 Jan 2100 12:00:00 UTC; path=/';

        });
    }

});

Note that PHP verifies the cookie-accepted cookie to determine when to print the cookie notice HTML.

Add the style with a CSS file

The example-cookie-notice.css file applies the following style changes in with few lines:

  • Moves the cookie notice in a fixed position at the bottom of the viewport
  • Makes the cookie notice distinguishable from the page content

The content of the style file:

#cookie-notice{
    background: #eee;
    position: fixed;
    left: 0;
    bottom: 0;
    padding: 20px;
    width: 100%;
}
Our lightweight cookie notice with the Twenty Twenty WordPress theme.
Our cookie notice with the Twenty Twenty theme

How to support the most common caching plugins

When a caching plugin is active on WordPress, the PHP scripts usually used to generate the front-end pages are not executed or partially executed.

In these conditions, a cookie plugin cannot verify the cookie-acceptance cookie’s presence and determine whether to display or not the cookie notice.

There are two approaches to solve this problem. The first is to use JavaScript to verify the cookie-acceptance cookie. The second is to follow the custom solutions provided by the developer of the caching plugin in use.

WP Super Cache

In this case, you have to signal to WP Super Cache the cookies used by the cookie notice plugin with the procedure explained in this post. It’s a straightforward procedure that permanently solves the problem.

After implementing this procedure, WP Super Cache will serve a non-cached version of the page to the users that have the signaled cookie.

W3 Total Cache

With the W3 Total Cache plugin, the cookie notice plugin developer should use the “Page Fragment Cache” feature to solve the problem. Here you can find a custom support answer and here an official FAQ on this subject.

LiteSpeed Cache

With LiteSpeed Cache, the administrator should add the cookie in the Login Cache option provided by the plugin, available in the Cache administrative menu.

After implementing this change, LiteSpeed Cache will not serve cached pages to the user with the specified cookie.

WP Fastest Cache

With the WP Fastest Cache plugin, follow this procedure to exclude a cookie from the cache:

  1. Visit the WP Fastest Cache menu
  2. Select the Exclude tab
  3. Click on the Add New Rule button
  4. In the Exclude Page Wizard modal window, select “Contain” and enter the cookie name in the text field
  5. Save your changes
  6. Clear the cache

Handle complex scenarios

If you want a cookie notice that allows the user to enable or disable specific cookies or specific categories of cookies, I recommend you to proceed as follows:

  1. Create an interface where that user can enable and disable cookies or cookie categories.
  2. Use JavaScript to store the selection of the user. Save the selection in multiple cookies or in a cookie that contains serialized data.

The PHP part should then verify which cookies or cookie categories are enabled and run the related scripts. For example, if the “Analytics” cookie category is allowed, print the related “Analytics” tracking code. Repeat the same process for all the other cookie categories.

Other performance improvements

The current example plugin load two resources in the front-end, the example-cookie-notice.js JavaScript file, and the example-cookie-notice.css style file.

You can reduce the number of files loaded in the front-end and increase the website’s performance by directly adding the CSS via JavaScript.

This example demonstrates how to augment our JavaScript file to include CSS in the page dynamically.

window.addEventListener('load', function() {

    let bt = document.getElementById('accept-cookie');
    if(bt){
        bt.addEventListener('click', function(){

            //close the cookie notice
            document.getElementById('cookie-notice').remove();

            //set the cookie
            document.cookie = 'cookie-accepted=1; expires=Thu, 1 Jan 2100 12:00:00 UTC; path=/';

        });
    }

    //Add the style rules
    let css = '';
    css += '#cookie-notice{';
    css += 'background: #eee !important;';
    css += 'position: fixed !important;';
    css += 'left: 0 !important;';
    css += 'bottom: 0 !important;';
    css += 'padding: 20px !important;';
    css += '}';

    //Add the style element to the DOM
    let style = document.createElement('style');
    style.innerHTML = css;
    style.id = 'tnt-style';
    document.head.appendChild(style);

});

Here you can download a zipped archive that includes the complete lightweight cookie notice WordPress plugin explained in this tutorial.