Add new GA4 script to WordPress

<?php
add_action('wp_print_scripts', 'inline_scripts');
function inline_scripts(){
	//Only track if not logged in or is a customer
	global $current_user;
	if ( !isset( $current_user->roles[0] ) || $current_user->roles[0] == 'customer' ) {
	?>
	<!-- Google tag (gtag.js) -->
	<script async src="https://www.googletagmanager.com/gtag/js?id=G-IDHERE"></script>
	<?php
	}
	?>
	<script>
	  window.dataLayer = window.dataLayer || [];
	  function gtag(){dataLayer.push(arguments);}
	  gtag('js', new Date());
	  gtag('config', 'G-IDHERE');
	</script>
	<?php
}

Leave a Reply

Your email address will not be published. Required fields are marked *