Adding Google Analytics To Your Website While Respecting “Do Not Track”

jz4ca36oj m

Adding Google Analytics to your website is a complicated business. No, you shouldn’t merely copy and paste the GA script provided by Google into your site. If you don’t believe me then this post is for you.

You see, Google Analytics does not automatically handle “privacy” for you. And, you really need to care about privacy even if your users don’t.

Before you start tracking users you must consider the privacy concerns and the laws around tracking users. Legislation like GDPR and security breach notification laws are clear signals that privacy is serious (give these terms a Google).

Everyone has a responsibility to understand the reality of their privacy online. But, we, the website owners have a real responsibility too.

If you have even a small personal WordPress website you are no exception. You need to navigate the complex world of online privacy laws.

However, adding respectful privacy controls to your website and tracking users on your website doesn’t have to be stressful. If it is stressful to you then don’t add tracking.

For those who dare track their users let’s look at adding Google Analytics to your site via a custom script that: Uses Google privacy controls and disables Google Analytics if the end-user has not explicitly agreed to be tracked.

Let’s get on with the JavaScript and HMTL. Then we can wrap everything up into a WordPress plugin. Note lines 6, 10, and 22 where you must replace GA_MEASUREMENT_ID with your GA tracking ID. Also, in this example, we MUST add the script immediately after the opening <body> tag.

To add proper privacy controls the script checks for a site provided DNT cookie (this cookie is custom) and checks the browser’s “Do Not Track” setting.

<!DOCTYPE html>
<html lang="en">
<head></head>
<body>
    <!-- Global site tag (gtag.js) - Google Analytics -->
    <script async src="https://www.googletagmanager.com/gtag/js?id=GA_MEASUREMENT_ID"></script>
    <script>
    function ga_track(track){
        document.cookie = !track ? 'DNT=1;path=/' : 'DNT=0;path=/'; 
        window['ga-disable-GA_MEASUREMENT_ID'] = !track;
        document.body.classList.add(!track ? 'ga-not-tracking' : 'ga-is-tracking');
        document.body.classList.remove(track ? 'ga-not-tracking' : 'ga-is-tracking');
    }
    
    document.body.classList.add(navigator.doNotTrack !== '1' ? 'ga-dnt-0' : 'ga-dnt-1');
    ga_track(document.cookie.indexOf('DNT=0') !== -1 && navigator.doNotTrack !== '1');
    
    window.dataLayer = window.dataLayer || [];
    function gtag(){dataLayer.push(arguments);}
    gtag('js', new Date());

    gtag('config', 'GA_MEASUREMENT_ID');
    </script>

    <div id="js-ndt-box">
        <p>I want to track your every move on this website but I have a <a href="/privacy-policy">Privacy Policy</a> so you should feel safe.</p> 
        <button onclick="ga_track(true)">Track Me</button>
        <button onclick="ga_track(false)">Do Not Track Me</button>
    </div>

    <!-- Your site's content -->
</body>
</html>

As you can see, the script looks for the cookie named DNT with a value of 0 (line 16). Then the script looks for the browser’s “Do Not Track” privacy setting (also line 16). If the “Do Not Track” setting is active we will always block tracking, even if the cookie “says” you can track the user.

document.cookie.indexOf('DNT=0') !== -1 && navigator.doNotTrack !== '1'

When either the DNT cookie or browser’s “Do Not Track” setting has a value of 1 our Google Analytics script will not send any data because we set the special GA disabling variable:

window['ga-disable-GA_MEASUREMENT_ID'] = true;

In this example, we also implement those “Track Me” and “Do Not Track Me” buttons. We use the buttons to set the DNT cookie’s value with JavaScript to 0 or 1 to enabled or disable Google Analytics tracking (again, only if “Do Not Track” is also disabled).

To pretty things up a bit, you can add your own CSS to customize the aesthetics. For example, you might add the following CSS using the helper classes added by the JavaScript in the script.

.ga-dnt-1 #js-ndt-box {
  display: none;
}

#js-ndt-box {
  padding: 20px;
  position: fixed;
  width: 100%;
  bottom: 0;
  right: 0;
  z-index: 2;
  background: #fff;
  box-sizing: border-box;
}

After making any edits to the script (you should as the example has been playful and snarky) you will want to be 100% certain you have things just right from a privacy control standpoint. To make sure everything is running as expected use Google Chrome and install the Google Analytics Debugger. Once installed and enabled you can use the extension to see how and when tracking is used in Chrome’s DevTools console.

Creating a WordPress Plugin for GA Tracking

Wrapping things up for WordPress, let’s create a plugin from the example script. But first, validate your theme is using the WordPress function wp_body_open(). If the function is not apart of your theme add it right after the opening of each <body> tag.

<?php
/**
 * Plugin Name: My Google Analytics
 * Version: 1.0.0
 * Description: Adds Google Analytics tracking.
 * Author: Kevin Dees
 * Author URI: https://kevdees.com/
 */
function ga_tracking_code() {
    $ga_id = defined('GA_MEASUREMENT_ID') ? GA_MEASUREMENT_ID : 'YOUR_TRACKING_ID_HERE';

    echo "<!-- Global site tag (gtag.js) - Google Analytics -->
        <script async src=\"https://www.googletagmanager.com/gtag/js?id={$ga_id}\"></script>
        <script>
          function ga_track(track){
              document.cookie = !track ? 'DNT=1;path=/' : 'DNT=0;path=/'; 
              window['ga-disable-{$ga_id}'] = !track;
              document.body.classList.add(!track ? 'ga-not-tracking' : 'ga-is-tracking');
              document.body.classList.remove(track ? 'ga-not-tracking' : 'ga-is-tracking');
          }
          
          document.body.classList.add(navigator.doNotTrack !== '1' ? 'ga-dnt-0' : 'ga-dnt-1');
          ga_track(document.cookie.indexOf('DNT=0') !== -1 && navigator.doNotTrack !== '1');
          window.dataLayer = window.dataLayer || [];
          function gtag(){dataLayer.push(arguments);}
          gtag('js', new Date());
        
          gtag('config', '{$ga_id}');
        </script>";

    echo '<div id="js-ndt-box"><p>I want to track your every move on this website but I 
    have a <a href="/privacy-policy">Privacy Policy</a> so you should feel safe.</p> 
    <button onclick="ga_track(true)">Track Me</button><button onclick="ga_track(false)">Do Not Track Me</button></div>';
}

add_action( 'wp_body_open', 'ga_tracking_code' );

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.