In this post, we will talk about how to hack the Mediawiki Template to include Google Analytics without tracking the sysop user. The better way is, obviously, to use the GoogleAnalytics Extension (which would be discussed in a later post). This hack applies to Mediawiki 1.9.3+
In the mediawiki/includes/skin.php file, search for the function bottomScripts(). You will see something like:
/** * This gets called shortly before the tag. * @return String HTML-wrapped JS code to be put before */ function bottomScripts() { global $wgJsMimeType; $bottomScriptText = "\n\t\t if (window.runOnloadHook) runOnloadHook ();\n"; wfRunHooks( 'SkinAfterBottomScripts', array( $this, &$bottomScriptText ) ); return $bottomScriptText; } |
Now, define a new function addGoogleAnalytics() with the following code, we will call it later in the bottomScripts() function:
/** * This function will embed the Google Analytics Tracking Code in Mediawki * We will call it in the bottomScripts() function **/ function addGoogleAnalytics(){ $printGoogleAnalytics = “\n”; $printGoogleAnalytics .= “var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");\n”; $printGoogleAnalytics .= "document.write(unescape("<script src='" gaJsHost "google-analytics.com/ga.js' type='text/javascript'></script>"));\n”; $printGoogleAnalytics .= “\n”; $printGoogleAnalytics .= “\n”; $printGoogleAnalytics .= “try {\n”; $printGoogleAnalytics .= “var pageTracker = _gat._getTracker ("UA-XXXXXX-XX");\n”; $printGoogleAnalytics .= “pageTracker._trackPageview();\n”; $printGoogleAnalytics .= “} catch(err) {}\n”; return $printGoogleAnalytics; } |
In this function, replace “UA-XXXXXX-XX” with your own Web Property ID.
Now, all that is left to do is to call our own function addGoogleAnalytics() in the bottomScripts() function, and it will be done. So modify the bottomScripts() function to include the function call:
/** * This gets called shortly before the tag. * @return String HTML-wrapped JS code to be put before */ function bottomScripts() { global $wgJsMimeType, $gStr; $bottomScriptText = "\n\t\t if (window.runOnloadHook) runOnloadHook ();\n"; wfRunHooks( 'SkinAfterBottomScripts', array( $this, &$bottomScriptText ) ); // the following is the function call added by us $gStr = $this->addGoogleAnalytics(); return $bottomScriptText; } |
We are done. Nifty! Aint it 😉
Note: Due to embedding code in this post, the “->” in our function call is being displayed as “->”, do correct it.