How to add Google Analytics tracking code


By Shea Bunge

updated 12 months ago

When adding the Global Site Tag (gtag.js) script to your site for Google Analytics tracking, you want to put the tracking code just after the opening <head> tag.

You can achieve this using the wp_head action hook. Here's an example:

add_action( 'wp_head', function () { ?>

<!-- Global site tag (gtag.js) - Google Analytics -->
<script async src=""></script>
  window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments);}
  gtag('js', new Date());

  gtag('config', 'UA-XXXXXXXX-X');

<?php }, 1 );

Remember to replace UA-XXXXXXXX-X in the code above with your actual Tracking ID.

Did this answer your question?