Skip to content

Instantly share code, notes, and snippets.

@rmpel
Last active November 17, 2021 14:06
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save rmpel/208b1c019257a50c6a7390e3d2c414c9 to your computer and use it in GitHub Desktop.
Save rmpel/208b1c019257a50c6a7390e3d2c414c9 to your computer and use it in GitHub Desktop.
GA4 Tracker mu-plugin
<?php // wp-content/mu-plugins/ga4.php - GA4 tracker boilerplate.
define('GA_NOT_LIVE', true); // remove for go
define('GA4_MEASUREMENT_ID', 'G-XXXXXXXXXX'); // required
define('UA_PROPERTY_ID', 'UA-XXXXXXX-YY'); // optional
define('GA_ANONYMIZE_IP', true); // optional
define('GA_TRACK_ADMINS', false); // optional, defaults to true
define('GA_TRACK_EDITORS', false); // optional, defaults to true
// we need GA as first thing in the body
add_action('wp_body_open', 'GA4', ~PHP_INT_MAX);
// but not all sites have that, so fall back to first in footer.
add_action('wp_footer', 'GA4', ~PHP_INT_MAX);
function GA4() {
// remember that we did this, we only need it once;
static $done;
if ($done) {
return;
}
$done = true;
if (current_action() === 'wp_footer') {
print '
<!-- DEVELOPER NOTE: please add
<'.'?php do_action(\'wp_body_open\'); ?'.'>
directly after the <body> open tag in your theme. -->
'; }
$track = true;
// fallback for UA-only tracker, should not be, but well, you know, sometimes ...
$ga4_tracker = 'G-XXXXXXXXXX' === GA4_MEASUREMENT_ID ? UA_PROPERTY_ID : GA4_MEASUREMENT_ID;
$ua_tracker = defined('UA_PROPERTY_ID') && preg_match('/UA-[0-9]+-[0-9]+/', UA_PROPERTY_ID) && UA_PROPERTY_ID !== $ga4_tracker ? UA_PROPERTY_ID : false;
if (current_user_can('manage_options') && defined('GA_TRACK_ADMINS') && !GA_TRACK_ADMINS) $track = false;
if (current_user_can('edit_posts') && defined('GA_TRACK_EDITORS') && !GA_TRACK_EDITORS) $track = false;
if ( ! $track ) {
?><!-- Google Analytics is disabled for your user level -->
<script>window['ga-disable-<?php print $ga4_tracker; ?>'] = true;<?php if ($ua_tracker) { ?>window['ga-disable-<?php print $ua_tracker; ?>'] = true; <?php } ?></script><?php
}
?><!-- Global site tag (gtag.js) - Google Analytics 4 -->
<script async <?php print defined('GA_NOT_LIVE') ? 'disabled-' : '' ?>src="https://www.googletagmanager.com/gtag/js?id=<?php print $ga4_tracker; ?>"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){ dataLayer.push(arguments); }
gtag('js', new Date());
gtag('config', '<?php print $ga4_tracker; ?>', { 'anonymize_ip': <?php print json_encode(defined('GA_ANONYMIZE_IP') ? !!GA_ANONYMIZE_IP : false); ?> });
<?php if ($ua_tracker) { ?>gtag('config', '<?php print $ua_tracker; ?>', { 'anonymize_ip': <?php print json_encode(!!GA_ANONYMIZE_IP); ?> });<?php } ?>
</script>
<!-- End Google Analytics --><?php
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment