How to let your Visitor set an Opt-Out-Cookie for Google Analytics Tracking
How is using Google Analytics even possible in Germany?
you might ask. The answer is: It’s difficult! First, you are supposed to have a special contract signed with Google. Secondly, you need to anonymize your visitors IPs because IPs are considered personal data here. Thirdly, you are supposed to give your visitors the opportunity to object and opt-out by simply not using your site or informing them about Google Analytics Opt-Out Browser Add-On.
But we would not be the overachievers that we are if we’d not be aiming even higher, right? We want our visitor to opt-out on Google Analytics with just one click of a button, don’t we? Here’s how to do that.
We build the gaProperty and disableStr vars first for later use. We then check if the document has a specific cookie set with
document.cookie.indexOf(disableStr + ‘=true’) > -1
If this is the case, we disable tracking for this particular page and this particular property with
window[disableStr] = true;
We had to do this because the ga-optout-property only works on pages, not on sites.
Next we have the gaOptout-function. This is what executes when the visitor opts out of Google Analytics Tracking i.e. clicks the respective link or button. Inside the function we
- write the cookie we had been checking for earlier
- disable tracking for the page
- alert the visitor that tracking has been successfully disabled
The rest is Google Analytics Business as usual. The closure loading analytics.js, creation of the ga-object with the correct property and sending the pageview to analytics for tracking. Worth mentioning is that we send a please-anonymize-ip-request alongside the pageview to Google because that’s how we roll here in Germany.
When you are planning to use this with WordPress, you should save it as /js/ga.js into your child theme. You then need to enqueue to load the script in your child theme’s functions.php with
wp_enqueue_script( ‘ga-js’, get_stylesheet_directory_uri() . ‘/js/ga.js’, array(), ‘1.0’, true );
That should set you up for super Germany compatible Analytics Tracking without even installing a plugin.