How to Add Google Analytics/Tag Manager to WordPress via functions.php

Adding Google Analytics or Tag Manager to your WordPress website is an important step in tracking website traffic and gathering valuable data. By default, you can add Google Analytics or Tag Manager to your WordPress website through a plugin or by inserting the tracking code directly into the header.php file. However, if you prefer not to use a plugin or make changes to the header.php file, you can add Google Analytics or Tag Manager to your WordPress website via the functions.php file. This tutorial provides a step-by-step guide on how to add Google Analytics or Tag Manager to your WordPress website via functions.php.

Access your child’s theme functions.php via FTP or
via Appearance > Theme File Editor > Your child theme > functions.php

There are three places where you want to add the tracking code. When performance is important, I’d suggest adding it to wp_footer but this could result in potential data loss.

Carefully read where you need to place your analytical code. Based on the suggested placement, you can change it in the example code.

  1. Inside the head tag (wp_head)
  2. After the opening body tag (wp_body_open)
  3. Before the closing body tag (wp_footer)

Our HEAD code:

function hoolite_add_analytics_head_js() {
	?>
	<!-- Replace this with your Analytical HEAD code -->
	
	<?php
}
add_action( 'wp_head', 'hoolite_add_analytics_head_js', 11 );

Our BODY code:

function hoolite_add_analytics_body_js() {
	?>
	<!-- Replace this with your Analytical BODY code -->
	
	<?php
}
add_action( 'wp_footer', 'hoolite_add_analytics_body_js', 11 );

If you need to add multiple analytical codes, you can simply re-use the code snippet or combine it. But don’t forget to give it a unique name per function.

By adding Google Analytics or Tag Manager to your WordPress website via the functions.php file, you can track your website’s traffic and gather valuable data without relying on a plugin or making changes to the header.php file. By following the steps outlined in this tutorial, you can easily add Google Analytics or Tag Manager to your WordPress website and start tracking your website’s performance.

Remember to replace the tracking code in the code snippets with your own Google Analytics or Tag Manager tracking code before adding it to the functions.php file. This will ensure that you are accurately tracking your website’s traffic and gathering valuable data.


Thats it!

Support 🐶

If you found this article helpful, got a question or spotted an error/typo... Do well to leave your feedback in the comment section or help spread it by sharing this article. If you're feeling generous (and I hope you do) you can definitely help me by getting me a cup of coffee ☕.


You may like these too!

Leave a Reply

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