WordPress – How to add Google Analytics tracking code to page

The following code can be added to your theme’s functions.php file to add the Google Analytics tracking code to all front-end pages (not the back end wp-admin).

You will need a copy of your tracking code, which can be accessed from the Google Analytics dashboard under Admin -> Property -> Tracking Info.

GoogleAnalytics-TrackingCode1

The code

Add this code to your theme’s functions.php file – directly below the opening <?php line.

Replace the entire <script> with your Google Analytics tracking code.

function itsg_google_analytics() { ?>
<script>
  (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
  (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
  m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
  })(window,document,'script','//www.google-analytics.com/analytics.js','ga');

  ga('create', 'XX-XXXXXXXX-X', 'auto');
  ga('send', 'pageview');

</script>
<?php }
add_action( 'wp_head', 'itsg_google_analytics', 10 );

Generally yes – but for tracking codes they need to be as high up as possible to capture the statistics as completely as possible.

More specifically, Google requires the tracking code to be in the header if you want to verify the Google Webmaster Tools product for your website.