Where to paste the Google Analytics code in your WordPress plugins?

This is the most frequently asked question while setting up a Google Analytics for a WordPress blog.

Google used to acclaim putting it just before the </body> tag, because the original method they provided for loading ga.js getting blocked. The newer synchronous syntax, though, can safely be put in the head with minimal blockage, so the now the best recommendation is just before the </head> tag in header.php

<head> will add a little latency; in the footer will reduce the number of page views recorded at some small margin. It’s a tradeoff. ga.js is worryingly cached and present on a large percentage of sites across the web, so it’s often served from the cache, reducing latency to almost nil.

As a matter of personal preference, I would suggest including it in the <head>, but it’s really a matter of preference.

 

To go to header.php follow the below steps:

  • Log in into word press using your username and password
  • Go to Appearance
    • Click on Editor
    • Select the Footer (footer.php) or header.php
    • Copy the code above </head>

Sample Google analytic code from the registered account:

<script type=”text/javascript”>

  var _gaq = _gaq || [];
  _gaq.push(['_setAccount', 'UA-XXXXXXXX-1']);
  _gaq.push(['_trackPageview']);

  (function() {
    var ga = document.createElement(‘script’); ga.type = ‘text/javascript’; ga.async = true;
    ga.src = (‘https:’ == document.location.protocol ? ‘https://ssl’ : ‘http://www’) + ‘.google-analytics.com/ga.js’;
    var s = document.getElementsByTagName(‘script’)[0]; s.parentNode.insertBefore(ga, s);
  })();

</script>

This clearly a preference of following a way, but the best from Google Analytic’s and WordPress point of view  is suggested here.

Add comment