Skip to content

Instantly share code, notes, and snippets.

@rmpel
Created May 3, 2018 11:57
Show Gist options
  • Select an option

  • Save rmpel/e65c155df34b3a3876e247a9f0c19107 to your computer and use it in GitHub Desktop.

Select an option

Save rmpel/e65c155df34b3a3876e247a9f0c19107 to your computer and use it in GitHub Desktop.
Make Google Analytics listen to Browser "Do Not Track" in WordPress
<?php
add_filter('opt_out_settings', function($settings) {
// this will work in most sites with a plugin to use Google Analytics.
$settings['id'] = autodetect_google_analytics_code();
// OR!
// use this line to be sure;
$settings['id'] = 'UA-1234567-89'; // <-- your analytics property code here
// OPTIONAL: use a cookie to disable Analytics
$settings['cookie_name'] = false; // set a cookie name here defined by your custom cookie-bar
$settings['cookie_value'] = false; // set the value to look for when analytics should be OFF.
return $settings;
});
add_action('wp_head', function(){
$id = $cookie_name = $cookie_value = '';
extract(apply_filters('opt_out_settings', compact('id', 'cookie_name', 'cookie_value')));
if ($id) {
?><script id="ga-opt-out">
(function(_d, _w) {
var dnt = false;
if ('msDoNotTrack' in navigator) dnt = (navigator.msDoNotTrack === 'on' || navigator.msDoNotTrack === 'yes' || navigator.msDoNotTrack === "1" || navigator.msDoNotTrack === 1);
if ('doNotTrack' in navigator) dnt = (navigator.doNotTrack === 'on' || navigator.doNotTrack === 'yes' || navigator.doNotTrack === "1" || navigator.doNotTrack === 1);
if ('doNotTrack' in window) dnt = (window.doNotTrack === 'on' || window.doNotTrack === 'yes' || window.doNotTrack === "1" || window.doNotTrack === 1);
<?php if ($cookie_value && $cookie_name) { ?>
dnt = dnt || _d.cookie.match(/(^|[; ])<?php print preg_quote($cookie_name); ?>=<?php print preg_quote($cookie_value); ?>(;|$)/);<?php }
?> _w['ga-disable-<?php print esc_attr($id); ?>'] = dnt;
})(document, window);
</script><?php
}
}, ~PHP_INT_MAX);
function autodetect_google_analytics_code() {
global $wpdb;
$uas = $wpdb->get_col("SELECT option_value FROM {$wpdb->options} WHERE option_value LIKE '%UA-%'");
$uas = array_map(function($el) { return preg_match('/(UA-[0-9]+-[0-9]+)/', $el, $m) ? $m[1] : false; }, $uas);
$uas = array_unique($uas);
$uas = array_filter($uas);
$uas = array_values($uas);
if (count($uas) === 1) {
return $uas[0];
}
return false;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment