How to add Google Analytics tracking code

Avatar

By Shea Bunge

updated 3 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="https://www.googletagmanager.com/gtag/js?id=UA-XXXXXXXX-X"></script>
<script>
  window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments);}
  gtag('js', new Date());

  gtag('config', 'UA-XXXXXXXX-X');
</script>

<?php }, 1 );

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

Did this answer your question?