How To Add A GDPR Consent Banner To A WordPress Website With Google Analytics

This tutorial will walk-through creating and adding a cookie-consent banner to make websites compliant with the new GDPR regulations in effect from 25 May 2018. You can read more about the GDPR regulation on the Information Commissioner Office’s website.

This tutorial will focus on making WordPress websites which utilise Google Analytics for monitoring traffic to their website GDPR compliant. We will achieve this by creating a cookie banner which asks the user for consent. If, and only if, the user accepts the cookie notice will data be sent to Google Analytics. If the user ignores the banner, or does not accept the cookie notice, data sent to Google Analytics will be anonymised.

This is deemed sufficient to be GDPR compliant because a user’s IP address is considered as personally identifiable information. Collecting traffic statistics for a website is a legal practise if it is to improve the service and content delivered to users/customers. However, Google uses this traffic information to serve advertisements and also improve data collection in the Google Analytics dashboard. For example, the “new user vs. returning user” statistic uses a combination of IP address, cookies and geographic information to determine which category a user falls in to.

Finally, we will also create a basic WordPress page template which will allow users to later opt-in and opt-out. This is also a requirement placed by the new May 2018 GDPR regulation, as previously an assumed opt-in cookie banner was sufficient.

How to add a GDPR cookie-consent banner to a WordPress website using Google Analytics

Step 1: Add the following <script> tag to your footer.php, just before the closing </body> tag:


<script type="text/javascript" id="cookiebanner"
  src="https://cdn.jsdelivr.net/gh/dobarkod/cookie-banner@1.2.2/dist/cookiebanner.min.js"></script>

Alternatively, the recommended approach is to download the package Cookie Banner by dobarkod on GitHub and include either the cookiebanner.js or cookiebanner.min.js files in your functions.php file as follows:


wp_enqueue_script( 'cookie-banner', get_stylesheet_directory_uri() . '/scripts/cookiebanner.min.js', array(), null, true);

This will enqueue the Cookie Banner package on to every page of your website.

Step 2: Create a new JavaScript file, mine is called default.js and also enqueue it in you theme’s functions.php file. This time, you also need to include jQuery as a dependency as follows:


wp_enqueue_script( 'default', get_stylesheet_directory_uri() . '/js/default.js', array('jquery'), null, true);

Step 3: Inside the default.js file, initialise a new cookie banner with the following code:


var options = {
	message: "This website would like to use cookies to enhance your experience.",
	moreinfo: "/privacy/",
	debug: false,
	closeText: "Accept"
};
var cb = new Cookiebanner(options); cb.run();

The above code creates a new cookie banner with the message “This website would like to use cookies to enhance your experience.” along with a link to the Privacy Page located at mywebsite.com/privacy and the acceptance text as “Accept”.

With this code added, you can refresh your website and notice the cookie banner appear at the bottom of the screen.

Step 4: When the user clicks the “Accept” button a cookie called “cookiebanner-accepted” is stored in the user’s browser. The documentation for cookie banner by dobarkod explains this in more detail.

If the cookie already exists, the banner will not display.

By default, the cookie never expires, however you can modify this by passing a property to options called expires with either a UTC Date object or the seconds until expiry.

Step 5: Next create a new page template. For example: page-my-privacy.php and follow the template for your theme. In the content of the page template, add the following code:


You <span class="myPrivacy_userHasOptedIn"></span> opted in to the use of cookies.</br />
<span class="myPrivacy_showOptOut"><a onclick="myPrivacy_optOut()">Click here</a> to opt-out from cookies.<br /></span>
To request any personal data we may hold on you, please <a href="<?php echo get_home_url(); ?>/contact">contact us</a>.

This HTML code renders three lines of code. The first line is always displayed and tells the user if they have accepted the cookie notice. The second line only displays if the user has consented to the cookie notice, and gives the option to revoke the consent. And the final line always displays, and advises the user on how to request any personal data held. How to process data requests will depend on the nature of your website or business, and is not covered in this post.

Step 6: The above template will not work by itself. We need to use JavaScript.

Head back to the default.js file you created earlier and add the following code:


var hasUserOptedIn = (document.cookie.indexOf('cookiebanner-accepted') > -1);

var userHasOptedInText = hasUserOptedIn ? "have" : "have not";
jQuery('.myPrivacy_userHasOptedIn').text(userHasOptedInText);

function myPrivacy_optOut() {
    deleteCookie('cookiebanner-accepted');
    alert("You have succesfully been opted out");
}

function deleteCookie(cookieName) {
    document.cookie = name + '=;expires=Thu, 01 Jan 1970 00:00:01 GMT;';
};

jQuery('.myPrivacy_showOptOut').css("display", hasUserOptedIn ? "" : "none");

This code determines if the user has accepted the cookie notice by checking if the cookiebanner-accepted cookie has been set (as explained earlier). It also uses jQuery to set the text to notify the user whether they have or have not opted in.

The function myPrivacy_outOut() is triggered onclick to allow the user to opt-out. This is done by deleting the cookie.

Finally, the last lines uses jQuery to hide/display the option to opt-out based on whether the user has opted in.

Step 7: Remember, you’ll need to create a blank page from the WordPress dashboard using the page-my-privacy.php template above and make it accessible so that users can opt-in and opt-out.

Step 8: With the basics of opting in to cookies configured, we need to make some modifications to our Google Analytics codes to respect whether a user has opted in or not. This step is simple.

Modify your Google Analytics tag code to look like the following:


<script>
    (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
        (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
        m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
    })(window,document,'script','https://www.google-analytics.com/analytics.js','ga');

    ga('create', 'UA-00000000-1', 'auto');
    ga('set', 'anonymizeIp', true);

    if (document.cookie.indexOf('cookiebanner-accepted') > -1) {
        console.info('You have opted in to Google Analytics tracking. To opt out, please visit our Privacy page.');
        ga('set', 'anonymizeIp', false);
    }

    ga('send', 'pageview');
</script>

The only difference between this and the standard tag is that all IP addresses are anonymised by default. If the cookiebanner-accepted cookie has been set, this means that the user has opted-in so the anonymised IP configuration is reversed.

Please remember this post is offered as guidance only and does not represent legal advice in any capacity. Following this guide does not guarantee that your website is GDPR-compliant. For professional advice, I recommend Computer Palm.

Subscribe to Email Updates