How to install Google Analytics on MediaWiki Monobook

Mediawiki has a few extensions to install Google Analytics. The problem is that the analytics code is inserted into the content rather than just before the closing head tag like it should be. Here’s how I install the tracking code to the default skin MonoBook or my own skins based on MonoBook.

1. Open the skin file (skins/Monobook.php)
2. Find the function called setupSkinUserCss.
3. At the bottom of this function right after a line that looks like this

$out->addStyle( 'monobook/IE70Fixes.css', 'screen', 'IE 7' );

insert the following code:

$out->addHeadItem('analytics',
            '<script type="text/javascript">'."
   var _gaq = _gaq || [];
  _gaq.push(['_setAccount', 'UA-0000000-0']);
  _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>"
        ); 

4. Change the UA-0000000-0 to your own analytics code.
5. Save and test. That’s it!