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.


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() { ?>
  (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),

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

<?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.