Google Analytics

Most commonly used method of implementing Google Analytics to a site is by adding the global site tag, otherwise known as gtag.js.

Global site tag should be placed immediately after the <head> tag of every page, the wp_head action with a high priority is a good action to do that for WordPress:

PHP
Adding gtag.js to child theme’s functions.php
/**
 * Google Analytics.
 */
add_action('wp_head', function() {
  if(is_user_logged_in()) {
	return;
  }
  ?>
  <!-- Global site tag (gtag.js) - Google Analytics -->
  <script async src="https://www.googletagmanager.com/gtag/js?id=GA_MEASUREMENT_ID"></script>
  <script>
	window.dataLayer = window.dataLayer || [];
	function gtag(){dataLayer.push(arguments);}
	gtag('js', new Date());
	gtag('config', 'GA_MEASUREMENT_ID');
  </script>
  <?php
}, 5);

The 2 instances of GA_MEASUREMENT_ID should be replaced with your Google Analytics property ID that looks something like this: UA-123123-3.

The wp_head action is executed on every page (but not admin dashboard) so this one snippet ensures all your posts and pages are tracked.

The snippet includes a condition if(is_user_logged_in()) { return; } – this prevents logged in users from being tracked. In most cases this is just you, the site administrator. In case you have many users on the site and would like to track their pageviews, then this block can be removed.

If you’re looking to implement Universal Analytics (analytics.js) then it can be implemented in a similar manner, but you’re most likely looking at something outdated, because it’s over 7 years old and gtag.js has effectively replaced it.

Same goes for Google Tag Manager (gtm.js), the gtag.js is a newer solution that can probably get the job done.

If adding PHP code to your server files is too complicated or you lack access, then there are multiple plugins out there that can achieve the same thing.

Google Site Kit is a plugin that can integrate your WordPress site with various Google services and get the statistics straight from the administration panel and individual pages.

Leave a comment

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