Skip to content

Instantly share code, notes, and snippets.

@damiencarbery
Last active March 17, 2019 16:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save damiencarbery/f658fe43035c0c747295ae66f199d5b9 to your computer and use it in GitHub Desktop.
Save damiencarbery/f658fe43035c0c747295ae66f199d5b9 to your computer and use it in GitHub Desktop.
Google Analytics – To filter your IP from GA logs you must not anonymize your IP in your ga() or gtag() call - filter out your IP with GDPR compliance: X https://www.damiencarbery.com/2019/03/google-analytics-filter-out-your-ip-with-gdpr-compliance/
<?php
/*
Plugin Name: Google Analytics with anonymize
Plugin URI: https://www.damiencarbery.com/
Description: Anonymize all visitor IPs except IPs or IP ranges in a set list.
Author: Damien Carbery
Author URI: https://www.damiencarbery.com
Version: 0.1
*/
add_action( 'wp_head', 'gaa_add_ga_tags_with_anonymize' );
function gaa_add_ga_tags_with_anonymize() {
$ga_tracking_id = 'UA-1234567-1';
// Can exclude IPs or a range.
$excluded_ips = array( '123.231.45.112', '132.211.55.' );
$anonymize_ip = true;
$gtag_config = sprintf( "gtag('config', '%s', { 'anonymize_ip': true });", $ga_tracking_id );
foreach ( $excluded_ips as $ip ) {
$strpos = strpos( $_SERVER['REMOTE_ADDR'], $ip );
//printf( '<!-- %s - %s = %s -->%s', $_SERVER['REMOTE_ADDR'], $ip, var_export( $strpos, true ), "\n" );
if ( 0 === strpos( $_SERVER['REMOTE_ADDR'], $ip ) ) {
$anonymize_ip = false;
$gtag_config = sprintf( "gtag('config', '%s');", $ga_tracking_id );
break;
}
}
?>
<script async src="https://www.googletagmanager.com/gtag/js?id=<?php echo $ga_tracking_id; ?>"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
<?php echo $gtag_config; ?>
</script>
<?php
}
gtag('config', 'UA-1234567-1', { 'anonymize_ip': true });
gtag('config', 'UA-1234567-1');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment