How to put the GoogleAnalytics code on MediaWiki into header instead of body

Bookmark and Share

There are to ways to enable GoogleAnalytics for MediaWiki:

One is to use the extension Google Analytics Integration – it’s easy and works fine, but puts the script into the pages body instead of the header. That makes no difference in regards of it working properly, but it’s not the way Google wants us to do it.
The alternative is to just put the code into the skin.
Let’s say you’re using the Vector skin. Open the file /skins/Vector.php and search for this text:

$out->addHeadItem( 'csshover',
'<!--[if lt IE 7]><style type="text/css">body{behavior:url("' .
htmlspecialchars( $wgLocalStylePath ) .

Below it, enter the following (while replacing the profile data with yours, of course)

   $out->addHeadItem( 'analytics',
            '<script type="text/javascript">'."

  var _gaq = _gaq || [];
  _gaq.push(['_setAccount', 'UA-00000000-1']);
  _gaq.push(['_setDomainName', '']);
  _gaq.push(['_setAllowHash', 'false']);

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


Lastly, remove any usage of GoogleAnalytics related extensions from your LocalSettings.php to prevent double-use of the script. Now check your real-time stats in GoogleAnalytics to see if the script is active.

Tagged , , , , , . Bookmark the permalink.

One Response to How to put the GoogleAnalytics code on MediaWiki into header instead of body

  1. Dennis says:

    Works on my wiki with version 1.22.2. Thanks a lot!!

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>