I have a modest blog. One day I might care about Google Anaylitcs. For now, my basic needs are:
- Add a GA global tag to the site
head
. - Present users with a way to opt-out of GA for my site.
- Display this option on the Privacy Policy page -
Settings > Privacy
.
For this, I'm using:
wp_head
to add the Google scripts - one for tracking + one for opt-out.get_option
to find the Privacy Policy page and conditionally add the opt-out script.add_shortcode
for placing the opt-out link anyewhere needed.
To test if things are working:
- Check the GA global tag appears on all site pages.
- Check the GA opt-out script appears on just the Privacy Policy page.
- Check that when user clicks the opt-out, an alert is displayed.
- Use your browser's dev tools to check for the
ga-disable
cookie.
In Chrome: Dev Tools > Application tab > Left nav > Storage: Cookies > Site Name
// Add GA Global Tag to site `head`
// Replace 2 instances of `UA-XXXXXXXXX-X` with property (account) ID.
function knotty_ga_global_tag() {
?>
<!-- Global site tag (gtag.js) - Google Analytics -->
<script async src="https://www.googletagmanager.com/gtag/js?id=UA-XXXXXXXXX-X"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'UA-XXXXXXXXX-X');
</script>
<?php
}
add_action( 'wp_head', 'knotty_ga_global_tag', 1 );
// Opt-Out of GA for this site
// Since we are only presenting this option on the Privacy Page,
// we only need the GA opt-out script in this page's `head`
// https://wordpress.stackexchange.com/a/314372
$privacy_policy_page = get_option( 'wp_page_for_privacy_policy' );
if( $privacy_policy_page ) :
function knotty_ga_opt_out(){
?>
<!-- Disable Google Analytics for this site -->
<script>
// Replace `UA-XXXXXXXXX-X` with property ID
var gaProperty = 'UA-XXXXXXXXX-1';
var disableStr = 'ga-disable-' + gaProperty;
if (document.cookie.indexOf(disableStr + '=true') > -1) {
window[disableStr] = true;
}
function gaOptout() {
document.cookie = disableStr + '=true; expires=Thu, 31 Dec 2099 23:59:59 UTC; path=/';
window[disableStr] = true;
alert('Google Analytics has been disabled for this site.');
}
</script>
<?php
}
add_action( 'wp_head', 'knotty_ga_opt_out', 1 );
endif;
// Create `[ga_opt_out]' shortcode
function knotty_ga_opt_out_button() {
$return = '<a href="javascript:gaOptout()">Opt out of Google Analytics for this site</a>';
return $return;
}
// Register and initialize shortcode
function knotty_register_ga_opt_out() {
add_shortcode( 'ga_opt_out', 'knotty_ga_opt_out_button' );
}
add_action( 'init', 'knotty_register_ga_opt_out');