Hack: Adding Google Analytics Without Editing the Header File

What is the right way to add Google Analytics code? I’ve done it in the past by simply placing the code in the header.php file of my theme. This makes a lot of sense, especially if you have created your own theme or so extensively edited an existing one that you aren’t use a child theme at all, just your own version of the theme.

But what if you really want to keep your theme intact, and have created a child theme the proper way so that you have just a small collection of replacement files in the child theme folder? You could add header.php to that child theme, but that would mean overriding the default header.php, which has a lot of stuff in it.

So instead, add some PHP to the functions.php of your child theme. This will add the Google Analytics code to the header, but leave your main theme untouched. We’ll use the wp_head action hook.

add_action('wp_head', 'wpaction_add_google_analytics', 10);
function wpaction_add_google_analytics() {
	?>
	<script async src="https://www.googletagmanager.com/gtag/js?id=UA-XXXXXXX-XX"></script>
	<script>
		window.dataLayer = window.dataLayer || [];
		function gtag(){dataLayer.push(arguments);}
		gtag('js', new Date());
		gtag('config', 'UA-XXXXXXX-XX');
	</script>
	<?
}

Obviously, you need to insert your own Google Analytics code in place of my X-ed out version. You can actually use this for anything you want to add to the header.

Leave a Reply

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