A Bundle of Love - Get one year of Dynamic Shortcodes + Code Snippets Pro - for just $39
View Offer
A Bundle of Love - Get one year of Dynamic Shortcodes + Code Snippets Pro - for just $39
View Offer

How to add Google Analytics tracking code

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.

Related Articles