Configuration
Add this to functions/cookies.php in a custom theme, or create a custom plugin, and edit it accordingly:
<?php
add_action('init', function() {
if (!class_exists(CookieManager::class)) {
return;
}
// Set the text to show in the cookie UI popup (setContent() accepts either a string or a closure)
CookieManager::instance()->setContent(function() {
return get_field('cookie_notice_content', 'option');
});
// Configure tracking cookies
CookieManager::instance()->addTracker(
// Internal ID
'ga',
// Name displayed to the user
'Google Analytics',
// Code to run when accepted
"
(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', " . json_encode($_ENV['GOOGLE_ANALYTICS_CODE']) . ", 'auto');
ga('send', 'pageview');
",
// Code to run when rejected
"
var domain = document.location.hostname;
domain = '.' + domain.replace(/^www\./, '');
CookieManager.delete_cookie('_ga', '/', domain);
CookieManager.delete_cookie('_gat', '/', domain);
CookieManager.delete_cookie('_gid', '/', domain);
console.info('deactivated google analytics');
"
);
});
Deleting Cookies
When deleting cookies, you MUST get the domain and path correct. The example code (above) attempts to extract the domain automatically by stripping off www. if it exists. However, both Google and HotJar store cookies on the TLD - meaning this doesn't work for dev sites or staging sites. You can fix by defining the TLD in the .env file and using:
$tld = $_ENV['TLD'] ?? '';
CookieManager::instance()->addTracker(
'tracker',
'name',
'init...',
"
var tld = " . json_encode($tld) . ";
if (!tld) {
tld = '.' + document.location.hostname.replace(/^www\./, '');
}
CookieManager.delete_cookie('_ga', '/', tld);
CookieManager.delete_cookie('_gat', '/', tld);
CookieManager.delete_cookie('_gid', '/', tld);
");
This will use the TLD specified in .env. If there isn't one specified, it falls back to using the domain.