Skip to content

Instantly share code, notes, and snippets.

@dannydover
Created October 30, 2019 01:12
Show Gist options
  • Select an option

  • Save dannydover/9ac714edf8b662636bcf9f757316b0e7 to your computer and use it in GitHub Desktop.

Select an option

Save dannydover/9ac714edf8b662636bcf9f757316b0e7 to your computer and use it in GitHub Desktop.
<?php
/*
Plugin Name: Google Analytics Tracking Code MU-Plugin
Description: A must-use plugin that adds immutable Google Analytics tracking code.
*/
/* This plugin is used to ensure that Google Analytics is always present on the site (thus the use of a mu-plugin)
and to maintain the relationship between WordPress themes (design) and WordPress plugins (functionality) by keeping this
code out of the theme and in a plugin. */
/* If HTTP host URL contains either the strings "staging" or "local", do nothing.
In all other cases, add Google Analytics tracking code */
if ((strpos($_SERVER['HTTP_HOST'], 'staging') !== false) || (strpos($_SERVER['HTTP_HOST'], 'local') !== false)) {
// do nothing
} else {
// add Google Analytics tracking code
add_action( 'wp_head', 'google_analytics_tracking', 1 );
}
function google_analytics_tracking( $priority ) {
?>
<!-- Global site tag (gtag.js) - Google Analytics -->
<script async src="https://www.googletagmanager.com/gtag/js?id=UA-XXXXXXX-X"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'UA-XXXXXXX-X');
</script>
<?php
};
?>
// REMEMBER TO UPDATE UA CODE "UA-XXXXXXX-X" IN BOTH PLACES IN GIST ABOVE
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment