Analytics: Add Google Analytics Tracking Script to WordPress

Analytics add google analytics tracking script to wordpress image

Go ahead… give Google just a little more info.

What it does…

Adds Google Analytics tracking script to your site. NOTE: You’re gonna wanna add your own unique Google Analytics ID in the code, then let this snip take care of the rest.

How it does it…

Adds the tracking JavaScript code to the head of your site using `wp_head`, but only on Production (if using Env555), and only for logged-in users. (But you could edit those parts, if desired.)

See the code…

<?php

// Analytics: Add Google Analytics Tracking Script to Wordpress
// https://snipsnip.pro/s/168
/* Uses Env555, if available */
namespace yOFSQS53;

\add_action( 'wp_head', function () { 

	$gaID = "XXXXXXXXXXXX";
    
	$addCode = true;
	if (function_exists('\Env555\this_is_a_production_site')) { 
	    // only on production for logged out users
    	$addCode = (\Env555\this_is_a_production_site() && !\is_user_logged_in());
	}
	
	if ($addCode === true) {
?>

<!-- Analytics: Add Google Analytics Tracking Script to Wordpress - https://snipsnip.pro/s/168 -->
<script async src="https://www.googletagmanager.com/gtag/js?id=<?php echo $gaID; ?>"></script>
<script>
	window.dataLayer = window.dataLayer || [];
	function gtag(){dataLayer.push(arguments);}
	gtag('js', new Date());
	gtag('config', '<?php echo $gaID; ?>');
</script>

<?php } }, 1000 );