Extension talk:Google Analytics Integration/Archive

From mediawiki.org

Installation in 2015

Hi, With this code

// Add HTML code for any additional web analytics (can be used alone or with $wgGoogleAnalyticsAccount) $wgGoogleAnalyticsOtherCode = '<script type="text/javascript" src="https://analytics.example.com/tracking.js"></script>';

What should I add? the new google analytics tracking code? Which is <script>

 (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
 (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
 m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
 })(window,document,'script','//www.google-analytics.com/analytics.js','ga');
 ga('create', 'UA-59749174-1', 'auto');
 ga('send', 'pageview');

</script> — Preceding unsigned comment added by Bentstuart1600 (talk • contribs) 02:14, 15 February 2015

You don't need that for Google Analytics. Just set $wgGoogleAnalyticsAccount --Ike @ WikiWorks 05:47, 15 February 2015 (UTC)Reply
OK cheers.

Usage Direction Unclear

As the writing of this text, after you install it, you go to the "Usage" says to create a GA account, location the UA number, then follow the aforementioned installation instructions . . . that you just did? that's a loop. It doesn't say WHAT to do with either line legacy of the new ga.js, I understand to popular the US # in the LocalSettings, but there is no clear directions on what to do now.

Darrellx (talk) 17:05, 10 September 2014 (UTC)Reply

NOTE - Please install new version

Please install the latest version! As seen below - The initial release of the extension was not returning 'true' properly, which causes errors in MW 1.11+ and halts further processing on the specified Hook in every version! (not cool) →Tim LaquaTalk | contribs@15:23, 26 August 2007 (UTC)Reply

I installed this extension on my MW 1.11(Alpha). Got Following error.

(Note I have removed my hosting a/c name and put XXXXX instead for obvious reason.)

MediaWiki internal error.

Original exception: exception 'MWException' with message 'Detected bug 
in an extension! Hook googleAnalyticsHook failed to return a value; should 
return true to continue hook processing or false to abort.' in /home/XXXXX/public_html/wiki/includes/Hooks.php:133
Stack trace:
#0 /home/XXXXX/public_html/wiki/skins/MonoBook.php(225): wfRunHooks()
#1 /home/XXXXX/public_html/wiki/includes/SkinTemplate.php(463): MonoBookTemplate->execute('MonoBookTemplat...', Array)
#2 /home/XXXXX/public_html/wiki/includes/OutputPage.php(683): SkinTemplate->outputPage()
#3 /home/XXXXX/public_html/wiki/includes/Wiki.php(301): OutputPage->output(Object(OutputPage))
#4 /home/XXXXX/public_html/wiki/index.php(90): MediaWiki->finalCleanup()
#5 {main}

Exception caught inside exception handler: exception 'MWException' 
with message 'Detected bug in an extension! Hook googleAnalyticsHook failed 
to return a value; should return true to continue hook processing or false to abort.'
in /home/XXXXX/public_html/wiki/includes/Hooks.php:133
Stack trace:
#0 /home/XXXXX/public_html/wiki/skins/MonoBook.php(225): wfRunHooks()
#1 /home/XXXXX/public_html/wiki/includes/SkinTemplate.php(463): 
   MonoBookTemplate->execute('MonoBookTemplat...', Array)
#2 /home/XXXXX/public_html/wiki/includes/OutputPage.php(683): SkinTemplate->outputPage()
#3 /home/XXXXX/public_html/wiki/includes/Exception.php(86): OutputPage->output(Object(OutputPage))
#4 /home/XXXXX/public_html/wiki/includes/Exception.php(111): MWException->reportHTML()
#5 /home/XXXXX/public_html/wiki/includes/Exception.php(191): MWException->report()
#6 /home/XXXXX/public_html/wiki/includes/Exception.php(225): wfReportException()
#7 [internal function]: wfExceptionHandler()
#8 {main}

-Gautam

Thx! The posted code should be working now. →Tim LaquaTalk | contribs@02:47, 20 August 2007 (UTC)Reply

runonloadhook

Tim, thanks for making this great extension. If you look at the code of any page in MW, you'll see near the end:

<script type="text/javascript">if (window.runOnloadHook) runOnloadHook();</script>

Wouldnt using this hook (if possible) be a better way because GA advises to use the code just before the body tag? This hook is about just before the body tag. --Kenny5 19:11, 2 September 2007 (UTC)Reply

If you run this extension on 1.11alpha+, you'll notice that the GA code actually shows up BELOW that script line. I added a new hook to the core (SkinAfterBottomScripts) specifically designed for JS-powered analytics engines. I talked to the guys over at Google regarding the tag placement and they said that as long as Google is receiving data, the tag placement is fine. There are certain locations where the script will not be executed properly and that's why they say put it at the bottom. Either way, if you get data in your GA reports, you're good - and once 1.11 comes out, the extension utilizes the new hook that puts the script tag at the absolute bottom of the page. →Tim LaquaTalk | contribs@19:26, 2 September 2007 (UTC)Reply
Ah I see, great then. I'll wait for the upgrades then. Thanks for all your research in this. And I just checked and am getting the data even with my 1.9.3 (should have mentioned before) so this is great. This extension is great, I didnt have to alter the internal files in any way (which is always the goal). thanks again --Kenny5 19:35, 2 September 2007 (UTC)Reply

Bottom of page; older version

I installed this and the script is not at the bottom of the page--though fairly near it. I'm using version 1.8. Right now when I go to google analytics and click the "check status" button it says that the tracking code hasn't been detected. What I'm guessing is that the detection mechanism specifically is looking for this at the bottom of the page but that, regardless it is working. I hope!. Anyway, I'll verify by checking back with google analytics in a few days and see if they are gathering any datat. Then I'll report the results here. Thanks for the extension! --Matthew (76.27.82.88 04:33, 14 September 2007 (UTC))Reply

Let me know if you don't receive any data within 48 hours of installing the extension. GA seems to be 2-3 days behind at all times. It should work even though it's not at the bottom, I talked to the GA guys when I wrote the extension.  ;-) →Tim LaquaTalk | contribs@12:26, 15 September 2007 (UTC)Reply

New GoogleAnalytics script

Changing this part of the code will incorporate the new GoogleAnalytics script:

$funcOutput = "<script type=\"text/javascript\">\n".
"var gaJsHost = ((\"https:\" == document.location.protocol) ? \"https://ssl.\" : \"http://www.\");\n".
"document.write(unescape(\"%3Cscript src='\" + gaJsHost + \"google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E\"));\n".
"</script>\n".
"<script type=\"text/javascript\">\n".
"var pageTracker = _gat._getTracker(\"" . $googleAnalytics . "\")\n".
"pageTracker._initData();\n".
"pageTracker._trackPageview();\n".
"</script>\n";

--Jdj 02:21, 28 December 2007 (UTC)Reply

Implemented support for the new ga.js script in r29077. Thx for the note, I wasn't aware they had a new script available. Also, check the code - f/ large string chunks like that, HEREDOC syntax is much cleaner.  ;-) Tim Laqua talk 22:05, 30 December 2007 (UTC)Reply


Version 2 Compatibility?

A few days ago I upgraded to version 2 with my mediawiki 1.11.2 and my gumax skin. Google analytics says that it recognizes the code but it seems weird because my traffic has died. I know that one person registered this morning and two other people simply visited (I asked them to visit). Yet 5 hours later still no traffic. I know it's not the Google Analytics delay because my blog is showing healthy traffic.

Is there a compatibility issue with something? Any suggestions? [Ed D April 1, 2008] ...this is not an April Fools joke.

Do you define $wgGoogleAnalyticsAccount after the require_once( ... ) line? In previous versions, I didn't initalize that variable, so you could define your account number anywhere. Now, because the extensions initalizes $wgGoogleAnalyticsAccount to a blank string, you need to make sure that your assignment of $wgGoogleAnalyticsAccount is *after* the require_once( ... ) statement for this extension (as shown on the extension page). If that's not the issue, the only other thing I can think of is the GA delay (24-48 hours) and maybe your Blog is granted a higher priority or something due to either high traffic or high pagerank? I'm also not sure if there's any difference in stat lag based on what version of the GA script you're using. 2.0 of this extension is using the new GA script. I know there are people using this version on MW 1.11.2, so it's certainly not an incompatibility issue. Tim Laqua talk 11:48, 2 April 2008 (UTC)Reply


Turns my Main Page into log file

When I try to use this extension, it turns my Main Page into a log file that looks like the code in the php file. I've put the two php files in the right folder and pasted the script into localsettings.php along with my GoogleAnalytics id but it just doesn't seem to want to work for me. I am using MediaWiki 1.12 and the cavendish theme.

Do you have an example URL I could take a look at? Tim Laqua talk 20:45, 6 July 2008 (UTC)Reply

Same Problem for me

The code from the googleAnalytics.php-File is printed out instead of my Wiki-Site. And there is the response:
Warning: Cannot modify header information - headers already sent by (output started at /hp/ag/ac/li/www/georg/wiki/extensions/googleAnalytics/googleAnalytics.php:12) in /hp/ag/ac/li/www/georg/wiki/includes/WebResponse.php on line 10

This is usually caused by a bad download that has garbage at the top or bottom of the file (often a BOM). Try re-downloading the file and saving it - don't cut/paste the contents in to an editor (BOMs may result). Tim Laqua talk 20:45, 6 July 2008 (UTC)Reply

Mediawiki 12.0

I´ve got an unexpected error message with Mediawiki 12.0, having had any problems in the past with the installation of Google Analytics on other portals:

Warning: Unexpected character in input: '\' (ASCII=92) state=1 in 
/home/coastalz/public_html /benidormense/pool/extensions/googleAnalytics/googleAnalytics.php on line 2
Parse error: syntax error, unexpected T_STRING in 
/home/coastalz/public_html/benidormense/pool/extensions/googleAnalytics/googleAnalytics.php on line 2

Anybody any idea?? Could it be that it has to do anything with the fact that the domain actually is added on the server of another domain, thus being actually a subdomain?...

Thanks in advance for your comments, --Horst Salzwedel 20:32, 19 July 2008 (UTC)Reply

No rendering at all

Hello Tim,

I just installed your extension, and it is well identified by my MW 1.11.

But I don't get the code in my page and I was wondering if the monoBook.php framework was not missing a call... I saw in the doc something like wfRunHooks(...) and you don't mention it.

I followed your installation process step by step.

Michel Cadennes

P.-S. Could you explain to me the meaning of this syntax : <<<GASCRIPT ? Opening Buffer ?

Edit :

I got the hook to work ! But remains a problem wirh global variables (in LocalSettings.php i.e. $wgGoogleAnalyticsAccount) which are not handled by the callback... Argh !

Edit 2 :

OK. It works finally... Wow ! But Some hints remain mysterious =:o)

Please tell me how ...

Michel - I have the same issue. Please tell me/everyone else how to resolve it.

Cheers, Hughie

Doesnt show on Google Analytics

I followed your installation process step by step. But it doesnt work. Does anyone have more information? Thanks.--Swessels 10:24, 30 July 2008 (UTC)Reply

Have you waited a day? It might just take a little time to show up. Smaug 17:11, 30 July 2008 (UTC)Reply
Uh, yes :-) Its been almost a week now, still nothing.... --Swessels 06:35, 1 August 2008 (UTC)Reply
I've looked at the source code for my index page, and there is nothing in that showing the google code, so it seems asif the code is not "pasted" into every page. The extension is installed, when I look at the Special page: Version.--Swessels 08:42, 4 August 2008 (UTC)Reply
(continued at User_talk:Smaug#Doesnt_show_on_Google_Analytics) Smaug 15:35, 7 August 2008 (UTC)Reply

GA code not rendering? Do the require_once and then set the properties!

It doesn't work when you set the variables and then do the require_once. ~ Erik de Bruijn

Note: you may need to remove the pageTracker._initData(); line for Analytics to recognise the installation

I don't get Analytics to work. I did everything right, but I don't understand the line Note: you may need to remove the pageTracker._initData(); line for Analytics to recognise the installation. Can it be explaned a bit better? Where do I find this line? I think this is the thing I have to do, because that's the only thing that's left.

It seems to be my problem also. This line code pageTracker._initData(); is not available in both files googleAnalytics.i18n.php and googleAnalytics.php. Where should we delete this line? Thanks.

Yeah, that note is RIDICULOUS: what do "you may have to..." mean?? Either you have to or you don't have to, And if you have to remove that line, then why on earth is it there in the first place? Why don't the developers delete it so we don't need to delete it?? Why put there a line of code that one has to delete? It doesn't make any sense.

Yup, if anyone could expand on this that would be great! Since no such line exists in the download, perhaps we should be bold and delete that line from the install instructions? They could be simpler too btw! --Dmb 13:15, 7 September 2011 (UTC)Reply

Error loading special pages

I get this when I click the special pages link in the tool bar:

Warning: MessageCache::require(/home/netcai5/public_html/wiki/extensions/googleAnalytics/googleAnalytics.i18n.php) [messagecache.require]: failed to open stream: No such file or directory in /home/netcai5/public_html/wiki/includes/MessageCache.php on line 813

Fatal error: MessageCache::require() [function.require]: Failed opening required '/home/netcai5/public_html/wiki/extensions/googleAnalytics/googleAnalytics.i18n.php' (include_path='/home/netcai5/public_html/wiki:/home/netcai5/public_html/wiki/includes:/home/netcai5/public_html/wiki/languages:.:/usr/lib/php:/usr/local/lib/php:/home/netcai5/php') in /home/netcai5/public_html/wiki/includes/MessageCache.php on line 813

I think everything is installed correctly as google is receiving data. Any ideas? my page is viewable at www netcairns com Judson --70.233.161.254 02:02, 29 November 2008 (UTC)Reply

My guess is that you haven't downloaded the googleAnalytics.i18n.php file, which is also part of the extension. -- AttishOculus

Website-Overlay do not work

The script works fine, just the Website-Overlay function in google analytics interface is not avadible. is ist possible to change that? PHP 5.2.6, mw: 1.13.1. thanks --87.187.36.250 16:25, 28 March 2009 (UTC)Reply

Feature Request

Kudos! This is a great tool and saved me countless hours. Thank you!

Is there a way we can exclude certain pages, such as the user Login page? Or the main page?

Just installed extension in v1.14

I just installed the extension in v1.14 at Debatrix and only had one problem. Line 59 of the .php file had to be removed. I see the code on my main page, so now I am waiting the 24-48hrs for some results to show up. I will try to post an update in the next couple of days when I see how it works.--Jake4d 06:17, 8 May 2009 (UTC) P.S. Thanks in advance for the great extension.Reply

Just checked my account at Google Analytics and this extension is working beautifully. Thanks--Jake4d 02:19, 11 May 2009 (UTC)Reply

Feature request: Option to exclude user accounts

Can the code be modified so if we want we can exclude user accounts too? I'm also interested in seeing traffic from the external internet visitors that doesnt include logged in users and editors who are often the most frequent users of the site. --Kenny5 18:43, 28 July 2009 (UTC)Reply

Not working with PHP 5.3.0

This extension doesn't seem to work with the newest PHP version 5.3.0. I get an error message.

Can that be fixed? It would be a pity if I can't use this great extension anymore. --Plati123 11:42, 12 August 2009 (UTC)Reply

likewise here - I get this on the Main Page of my wiki:
Warning: Parameter 1 to efGoogleAnalyticsHookText() expected to be a reference, value given in  /Users/roger/Sites/xxxxxx/legacy/w/includes/Hooks.php on line 117

Warning: Parameter 1 to efGoogleAnalyticsHookText() expected to be a reference, value given in  /Users/roger/Sites/xxxxxx/legacy/w/includes/Hooks.php on line 117
MediaWiki internal error.

Exception caught inside exception handler
I'm running a local copy on OS X 10.6.1 (Snow Leopard) with: MediaWiki 1.15.1 (r4), PHP 5.3.0 (apache2handler), MySQL 5.1.39 --Junap 15:25, 10 October 2009 (UTC)Reply
To fix, edit googleAnalytics.php, and change line 23 from:
 function efGoogleAnalyticsHookText(&$skin, &$text='') {
to
 function efGoogleAnalyticsHookText($skin, &$text='') {

I had the same bug, same fix. Except it was line 35.--71.163.233.145 20:49, 8 March 2010 (UTC)Reply
This fixed the problem for me also. Shaun Clarke 03:26, 25 June 2010 (UTC)Reply
Fixed problem for me too. Just look for function efGoogleAnalyticsHookText and change the signature as specified above. --Slowpoison 23:01, 6 July 2010 (UTC)Reply

The error message here was PHP Warning: Parameter 1 to efGoogleAnalyticsHookText() expected to be a reference, value given in .../mediawiki-1.17a/includes/Hooks.php on line 133 with the offending call made from "extensions/googleAnalytics/googleAnalytics.php" line 24 of 59. This is based on the most current version of MediaWiki. --Carlb 14:23, 4 July 2010 (UTC)Reply

Not working with PHP 5.2.8 either (me thinks)

I have installed via instructions and the extensions shows up in my Version page, but no code shows up when I view source on any page.

You may want to tail -f /var/log/httpd/error_log to see what's going on. A completely-blank page (0 bytes) usually means there's a PHP Fatal error in the logs for that page, preventing any output from being generated. Without looking at the log file, that error could be anywhere. --Carlb 17:48, 4 July 2010 (UTC)Reply

How do I use this to limit GA results to a single category?

Rather than create a namespace so that there's a common URL pattern across all designated articles, I want to track Google Analytics for a specific MediaWiki category — can I do it with this extension or another? Thanks in advance. --Torley 21:25, 22 September 2009 (UTC)Reply

Probably not any extension. You'll have to change some code. --Choshi 13:27, 2 October 2009 (UTC)Reply

New GA Tracking code

Any plan to update this to use the new asynchronous GA tracking code? See http://code.google.com/apis/analytics/docs/tracking/asyncTracking.html

RoyLeban 21:07, 20 December 2009 (UTC)Reply

Using LocalSettings.php

Why do the instructions say to edit the source code rather than to set values in LocalSettings.php? Shouldn't both methods work? (I did it the way you said, just to make sure, but that means I have to edit the source each time I update the extension).

I agree this would be a good idea also. Shaun Clarke 03:26, 25 June 2010 (UTC) RoyLeban 21:10, 20 December 2009 (UTC)Reply

Replace xxxxxxx-x with YOUR GoogleAnalytics UA number

Can't this be set in LocalSettings.php like other extension configuration?

Anyone know if any developers are tracking this discussion page? Seems a lot of questions go unanswered here... --Dmb 13:20, 7 September 2011 (UTC)Reply

would it be slightly easier

would it be slightly easier if you allowed the user to specify the account # in their localsettings.php, instead of having to edit the googleAnalytics.php file? Thanks Bud0011 02:33, 23 February 2010 (UTC)Reply

It is just that the instructions are misleading. "require_once( "$IP/extensions/googleAnalytics/googleAnalytics.php" ); $wgGoogleAnalyticsAccount = "UA-xxxxxxx-3";" works fine. The account must be set AFTER the require_once, however. G.Hagedorn 01:50, 16 November 2011 (UTC)Reply

Question

We got this error when the extension crashed our wiki:

MediaWiki internal error.

Exception caught inside exception handler

We're using:

  • MediaWiki 1.15.1
  • PHP 5.3.1 (apache2handler)
  • MySQL 5.1.41

Appreciate any help. Thanks! Julia & Ted

Ah, we made the line 23 change above and it worked! -- Julia & Ted

Please verify "non-logged in" alternative files

Noticing that Extension:Google_Analytics_Integration#See also is offering alternate download of the extension files from sites.google.com. I'd feel more comfortable (and perhaps I'm not alone feeling insecure about this) if they were to be added to the svn instead. Thanks --SomaticJourney 06:20, 6 March 2010 (UTC)Reply

Looks like it's not a function of WMF to check extensions or put them all on svn. I took a look at the sites.google script and it seems to be genuine. I'm testing it out. If it works, I vote to merge $wgGoogleAnalyticsIgnoreUsers in to the code. --SomaticJourney 07:43, 6 March 2010 (UTC)Reply

Google has a new tracking code (when I checked on March 7, 2010)

I am using your development trunk r62858. Tracking wasn't working for me. Google analytics said that tracking was unknown. I noticed that the code this extension placed at the bottom of my main page did not match what google wanted me to insert manually. Here is your trunk r62858 code:

<script type="text/javascript">
var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
</script>
<script type="text/javascript">
var pageTracker = _gat._getTracker("{$wgGoogleAnalyticsAccount}");
pageTracker._initData();
pageTracker._trackPageview();
</script>

and here is the new google code:

<script type="text/javascript">
var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
</script>
<script type="text/javascript">
try {
var pageTracker = _gat._getTracker("UA-XXXXXXXX-X");
pageTracker._trackPageview();
} catch(err) {}</script>
try {

has been added

pageTracker._initData();

has been removed

} catch(err) {}

has been added

I made these changes in googleanalytics.php.

I also made the change to:

function efGoogleAnalyticsHookText($skin, &$text=) {

in googleanalytics.php as outlined earlier in this talk page(because I use php 5.3.0).

After that everything worked. --twinsenw

---(May 17,2010) -- Haides In my website, I need replace this code in googleAnalytics.php, then it worked. If you had enabled googleAnalytics extension, pls re-enable it in LocalSettings.php(comment it firstly)

				
$funcOutput = <<<GASCRIPT
<script type="text/javascript">

  var _gaq = _gaq || [];
  _gaq.push(['_setAccount', '$wgGoogleAnalyticsAccount']);
  _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>
GASCRIPT;

extension does not work

I created the /extensions/googleAnalytics/ folder, downloaded googleAnalytics.i18n.php & googleAnalytics.php into it, added require_once( "$IP/extensions/googleAnalytics/googleAnalytics.php" ); to the bottom of LocalSettings.php, set Account to my account #, AddASAC to false, IgnoreSysops to true, & IgnoreBots to true. The page says it should be working now, but instead URL/wiki/index.php/Main_Page says "MediaWiki internal error. Exception caught inside exception handler" and the Google Analytics Tracking Status says: "Tracking Not Installed (Last checked: Jul 14, 2010 12:59:58 AM ) The Google Analytics tracking code has not been detected on your website's home page. For Analytics to function, you or your web administrator must add the code to each page of your website." I have the Google Analytics Website URL for just the URL without the /wiki/ part, not sure that matters.

Probably, bug in PHP 5.3.3, see fix.
14 April 2011 - I installed the extension and it works! ~nels nelson my media wiki
I added the tracking code in googleAnalytics.php
The PHP bug was causing me problems, I fixed it (I had PHP 5.3.2).
The extension shows in Special:version
I then went to google and got the same message with a wierd date:
Tracking Not Installed Last checked: Dec 31, 1969 4:00:00 PM PST
"The Google Analytics tracking code has not been detected on your website's home page. For Analytics to function, you or your web administrator must add the code to each page of your website."
Any suggestions? Does it take a while to read my site? Bigbull 01:25, 16 September 2011 (UTC)Reply

New async code

I change the code to the new async GA:

$funcOutput = <<<GASCRIPT
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-XXXXXXXX-X']);
_gaq.push(['_setDomainName', 'domain.com']);
_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>
GASCRIPT;


And change:

//$wgHooks['SkinAfterBottomScripts'][]  = 'efGoogleAnalyticsHookText';
$wgHooks['SkinAfterContent'][]  = 'efGoogleAnalyticsHookText';


And:

//function efGoogleAnalyticsHookText(&$skin, &$text='') {
function efGoogleAnalyticsHookText(&$text='') {


For render the code near the body.

Anyone can tell me how must do for render inmediately before body tag?

Tracking for File Downloads

This extension works great for tracking wiki page views. However it doesn't seem to track direct file downloads. For example, it will track when someone goes to File:somefile.doc, but not when they click on Media:somefile.doc (which downloads the file directly). Is there any way to track this? --Gkullberg 16:57, 14 September 2010 (UTC)Reply

I added this before the </script> to trigger an event for file downloads
 $(document).ready(function(){ //track downloads
  $('a').filter(function() {
    //filter <a> elements by extension
    ext = new Array('avi','doc','docx','dot','dotx','exe','eml','mp4','m4v','mov','mpg','oft','ott','ppt','pptx','pdf','scr','xls','xlsx','zip');
    return (new RegExp('\\.'+ext.join('$|\\.')+'$', "i")).test($(this).attr('href'));
  }).click(function(e) {
    e.preventDefault();
    _gaq.push(['_trackEvent', 'Downloads', this.pathname]);
    setTimeout("document.location = '" + this.href + "'", 100);
  });
 });
Bwaindwain (talk) 18:42, 19 February 2014 (UTC)Reply

This is good, but doesn't quite work- it fires when going to the File:blah.pdf page as well as when clicking on the actual file to download. I also wonder if it could be more intelligent (not having to list all file extensions)

Very simple extension for Google Analytics

File 'extensions/GoogleAnalytics.php':

<?php
global $wgGoogleAnalytics;
$wgGoogleAnalytics = false;

$wgHooks['ParserAfterTidy'][]  = 'efGoogleAnalytics';

function efGoogleAnalytics() {
	global $wgOut;
	global $wgGoogleAnalytics;

	if (!$wgGoogleAnalytics) {
		$funcOutput = <<<GASCRIPT
<script type="text/javascript">
var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
</script>
<script type="text/javascript">
try{
var pageTracker = _gat._getTracker("UA-xxxxxx-x");
pageTracker._trackPageview();
} catch(err) {}
</script>
GASCRIPT;
		$wgOut->addScript($funcOutput);
		$wgGoogleAnalytics = true;
	}
	return true;
}
?>

Add in LocalSettings.php:

require_once($IP.'/extensions/GoogleAnalytics.php');

How to set the new asynchronous snippet before the head tag (mw < 1.17)

Thanks to RoanKattouw I've been able to set this extension to add the asynchronous snippet right before the head tag.

Before you find the new version of googleAnalytics/googleAnalytics.php

Modifications:

Let's hope this will be useful to others too :) --Mindrones 12:12, 8 November 2011 (UTC)Reply

<?php
if ( !defined( 'MEDIAWIKI' ) ) {
	die( 'This file is a MediaWiki extension, it is not a valid entry point' );
}

$wgExtensionCredits['other'][] = array(
	'path'           => __FILE__,
	'name'           => 'Google Analytics Integration',
	'version'        => '2.0.2',
	'author'         => 'Tim Laqua',
	'descriptionmsg' => 'googleanalytics-desc',
	'url'            => 'http://www.mediawiki.org/wiki/Extension:Google_Analytics_Integration',
);

$wgExtensionMessagesFiles['googleAnalytics'] = dirname(__FILE__) . '/googleAnalytics.i18n.php';

$wgHooks['BeforePageDisplay'][]  = 'efGoogleAnalyticsHookText';
$wgHooks['ParserAfterTidy'][] = 'efGoogleAnalyticsASAC';

# registered account
$wgGoogleAnalyticsAccount = "UA-XXXXX-X";

# to be used in case we had AdSense as well and have linked accounts, to enable tracking set this to true
$wgGoogleAnalyticsAddASAC = false;
$wgGoogleAnalyticsIgnoreSysops = true;
$wgGoogleAnalyticsIgnoreBots = true;

function efGoogleAnalyticsASAC( &$parser, &$text ) {
	global $wgOut, $wgGoogleAnalyticsAccount, $wgGoogleAnalyticsAddASAC;

	if( !empty($wgGoogleAnalyticsAccount) && $wgGoogleAnalyticsAddASAC ) {
		$wgOut->addScript('<script type="text/javascript">window.google_analytics_uacct = "' . $wgGoogleAnalyticsAccount . '";</script>');
	}

	return true;
}

function efGoogleAnalyticsHookText( $out ) {
	$out->addScript( efAddGoogleAnalytics() );
	return true;
}

function efAddGoogleAnalytics() {
	global $wgGoogleAnalyticsAccount, $wgGoogleAnalyticsIgnoreSysops, $wgGoogleAnalyticsIgnoreBots, $wgUser;
	if (!$wgUser->isAllowed('bot') || !$wgGoogleAnalyticsIgnoreBots) {
		if (!$wgUser->isAllowed('protect') || !$wgGoogleAnalyticsIgnoreSysops) {
			if ( !empty($wgGoogleAnalyticsAccount) ) {
				$funcOutput = <<<GASCRIPT
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', '$wgGoogleAnalyticsAccount']);
_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>
GASCRIPT;
			} else {
				$funcOutput = "\n<!-- Set \$wgGoogleAnalyticsAccount to your account # provided by Google Analytics. -->";
			}
		} else {
			$funcOutput = "\n<!-- Google Analytics tracking is disabled for users with 'protect' rights (I.E. sysops) -->";
		}
	} else {
		$funcOutput = "\n<!-- Google Analytics tracking is disabled for bots -->";
	}

	return $funcOutput;
}

///Alias for efAddGoogleAnalytics - backwards compatibility.
function addGoogleAnalytics() { return efAddGoogleAnalytics(); }

Difference between Urchin and Analytics.

Hi, My shared host uses Urchin to show how many visitors the wiki got, and a few weeks ago I started using this extension to use Google Analytics, but there's a difference between the results of Urchin v5.7 and Google Analytics. The difference is about 200 visits per day.

Anyone knows how can I fix it?

MW: 1.7 PHP: 5.2.17

Does not show up

Hi,

I've installed it correctly, using my GA ID and it shows up in version. However, it doesn't show up in GA, even after a week. When I use In-Page Analytics I get the following error:


We've identified problems in your setup. These may cause problems loading In-Page Analytics. Your site doesn't load ga.js from Google. If you host the Google tracking code on your own servers, it isn't updated automatically and can miss important changes. We didn't find a tracking snippet on your site. In-Page Analytics cannot load. Please make sure you have tracking installed correctly. If your snippet is included in a separate JavaScript file, you'll have to manually check it is being loaded correctly.


Its about this site. (20120312)

My personal suggestion to integrate Google Analytics in Mediawiki 1.17+

I've been working on Analytics integration all this morning, and tried several different configuration, such us editing "MediaWiki:Common.js" page, which resulted in integrating onli the ga.js script but not the other code, while the code posted above by Mindrones seemed to be work almost good, however with some problems:

  • ga.js was succesfully integrated in head section
  • other Analytics script code (var _gaq... etcetera) was integrated at the bottom of the body section

I tried to move to the head without success.

The only solution i've found to integrate G Analytics in Mediawiki 1.18.2 was to edit Vector.php file (because i'm using the vector theme of course).

At the beginning of the file, around line 40, you'll find:

                $out->addHeadItem( 'csshover',
		/*NOT INTERESTING STUFF FOR US HERE*/
		);

so at the line just ABOVE this $out add:

		$out->addHeadItem( 'analytics',
		'<script type="text/javascript">'."
		var _gaq = _gaq || [];
		_gaq.push(['_setAccount', 'UA-XXXXXXXX-X']); /* Fill here your UA id */
		_gaq.push(['_setDomainName', 'yourdomain.com']); /* This row is needed only if you want to monitor more subdomains, otherwise comment it out */
		_gaq.push(['_setAllowHash', 'false']);
		_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>"
		);

The your google analytics code will be integrated as google states. I know that would be better to keep MediaWiki core files as they come, and of course this is a "one size fit all" solution because then traffic from sysop, bureacrats or bots won't be filtered, and we can rely only on the Google automated "bot" filters that i (hope) are used by Analytics. However this is the only way i've found and i hope it'll help someone. --Frafor (talk) 12:49, 3 May 2012 (UTC)Reply

That's actually a pretty cool alternative to the extension. Thanks a lot! Cheers, --Till Kraemer (talk) 17:28, 6 September 2012 (UTC)Reply
Actually, you don't have to do this: simply go to https://www.google.com/analytics/web/#home/ and get the new async code and replace the HTML portion of the extension. It works even if placed at the bottom of your HTML, right before </body>. Wikihy com (talk) 13:48, 24 November 2013 (UTC)Reply

How to include async code in header

To use the instruction above for async analytics, use this snippet instead.

		$out->addHeadItem('analytics',"<script>
		(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
		(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
		m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
		})(window,document,'script','//www.google-analytics.com/analytics.js','ga');

		ga('create', 'UA-XXXXXXXX-X', 'yourdomain.com');/* Fill in your UA id and domain */
		ga('send', 'pageview');

		</script>"
		);

Error: Cannot modify header information

I have installed the extension following installation guide on MW 1.19.1. The page after loading shows several times:

Warning: Cannot modify header information - headers already sent by (output started at ~extensions/googleAnalytics/googleAnalytics.php:1) in ~includes/WebResponse.php on line 38

whats wrong and how to debug?--Juandev (talk) 21:19, 23 June 2012 (UTC)Reply

When I use the bug fix as having higher PHP version (5.3.6 (cgi-fcgi)) even MW version, the same warning comes, but I can se MW interface. Skin: Vector.--Juandev (talk) 21:39, 23 June 2012 (UTC)Reply

MobileFrontend conflict?

I've installed MobileFrontend extension on my website, for mobile users. Since then, almost all mobile traffic is not recognized by Google Analytics - down from few hundreds a day to almost zero, and it supposedly shows a matching drop in traffic. The mobile version definitely works and is being used. I checked it myself. So it seems the problem is in tracking. Any idea what might cause this?

MW 1.18.0 PHP 5.3.10 Osishkin (talk) 08:16, 1 March 2013 (UTC)Reply

Google Universal Analytics

Is Google Universal Analytics supported by this extension? If so how? Or what is the best way to set the hole Google Analytics javascript (so we can integrate the Google Universal Analytics script)?

Juswes (talk) 09:49, 5 July 2014 (UTC)Reply

I'd love an answer to that question as well. Thanks. -OlivierC Aug 23, 2014
No response in more than 5 months... is this extension still maintained? OlivierC (talk) 01:01, 14 December 2014 (UTC)Reply
I just submitted a patch for this (and more) https://gerrit.wikimedia.org/r/182749 --Toniher (talk) 21:29, 4 January 2015 (UTC)Reply

Failed instalation

Hi,

I downloaded your extension for 1.22 version, tried to install it at this 1.22.7 wiki. Unpacked the thing, placed the folder to /extensions and put my code into Localsettings. As you can see on the linked Special:Version page, the gadget is not installed. The google analytics account says that there is no page linked to it, nothing to measure. I am posting end of the LocalSettings.php, since I suspect them as a cause of the problem (I replaced the google acc. no with dots, that one is not a mistake). Did I miss some step? I waited 1 day....

End of LocalSettings.php

$wgTmpDirectory = "$IP/images/temp";
$wgPFEnableStringFunctions = true;
require_once "$IP/extensions/ParserFunctions/ParserFunctions.php";
require_once "$IP/extensions/WikiEditor/WikiEditor.php";
require_once("$IP/extensions/AddScript/AddScript.php");

# Enables use of WikiEditor by default but still allow users to disable it in preferences
$wgDefaultUserOptions['usebetatoolbar'] = 1;
$wgDefaultUserOptions['usebetatoolbar-cgd'] = 1;
 
# Displays the Publish and Cancel buttons on the top right side
$wgDefaultUserOptions['wikieditor-publish'] = 1;

# Displays the Preview and Changes tabs
$wgDefaultUserOptions['wikieditor-preview'] = 1;

# debugging
##$wgShowExceptionDetails = true;
##$wgDebugToolbar = true;

# povoleni uzivatelskych javascriptu
$wgAllowUserJs = true;

# cesta k favicone
$wgFavicon = "{$wgScriptPath}/favicon.ico";

# povoleni svg
$wgFileExtensions[] = 'svg';

require_once "$IP/extensions/googleAnalytics/googleAnalytics.php";
// Replace xxxxxxx-x with YOUR GoogleAnalytics UA number
$wgGoogleAnalyticsAccount = 'UA-.....-....'; 
// Add HTML code for any additional web analytics (can be used alone or with $wgGoogleAnalyticsAccount)
$wgGoogleAnalyticsOtherCode = '<script type="text/javascript" src="https://analytics.example.com/tracking.js"></script>';
 
// Optional configuration (for defaults see googleAnalytics.php)
// Array with NUMERIC namespace IDs where web analytics code should NOT be included.
$wgGoogleAnalyticsIgnoreNsIDs = array(500);
// Array with page names (see magic word Extension:Google Analytics Integration) where web analytics code should NOT be included.
$wgGoogleAnalyticsIgnorePages = array('ArticleX', 'Foo:Bar');
// Array with special pages where web analytics code should NOT be included.
$wgGoogleAnalyticsIgnoreSpecials = array( 'Userlogin', 'Userlogout', 'Preferences', 'ChangePassword', 'OATH');
// Use 'noanalytics' permission to exclude specific user groups from web analytics, e.g.
$wgGroupPermissions['sysop']['noanalytics'] = true;
$wgGroupPermissions['bot']['noanalytics'] = true;
// To exclude all logged in users give 'noanalytics' permission to 'user' group, i.e.
$wgGroupPermissions['user']['noanalytics'] = true;
 

Any help will be appreciated. Thank you! --Wesalius (talk) 06:57, 14 March 2015 (UTC)Reply

Code in wrong section <body>

I installed this extension and put code to LocalSettings.php

But on my page http://wiki.westeros.pl/ this code is showing inside <body> section at the bottom of source code.

How to move it to <head> section.

Google Analytics TOS

I want to mention about how Google Analytics requires agreement to a Terms of Service (https://www.google.com/analytics/terms/us.html) but I don't know where to write it in the instructions. I mention this because many websites fail to create a proper privacy policy to disclose its use, and that is a violation of section 7 of their terms. 2604:6000:1519:C006:58C6:2D10:DB2F:E0F5 22:37, 27 November 2015 (UTC)Reply

Not working

I've been searching a lot on how to set this up, and unfortunately i've hit a wall. Version reported by Special:Version is

Product Version
MediaWiki 1.26.2
PHP 5.5.9-1ubuntu4.14 (apache2handler)

Saved the uncompressed folder inside /extensions/googleAnalytics/ , and then editted the LocalSettings.php to add the provided code while replacing the sample of $wgGoogleAnalyticsAccount with my own code, and I get nothing.

In the Installed extensions section I can see the extension. Anything that could help? --Konsnos (talk) 10:50, 23 January 2016 (UTC)Reply

ga('require', 'displayfeatures');

There should be some way to insert the following JavaScript code before ga('send', 'pageview');:

   ga('require', 'displayfeatures');

This code is used for example for AdWords remarketing.

Instead of modifying this extension, we may consider to create an "universal" extension, which would insert any text specified in the LocalSettings.php (or in a referenced from LocalSettings.php text file) into given positions: after opening <body> tag, before </body>, and probably in other positions.

--VictorPorton (talk) 22:01, 26 January 2016 (UTC)Reply

Analytics grouping by category

I struggle to add grouping by category do GA Integration. I should add the code

ga('set', 'contentGroup1', 'My Group Name'); 

where My Group Name should be the first category name. I managed to add the code to googleAnalytics.hooks.php, but I'm unable to get name of the category. I use Mediawiki 1.26.2. I tried with $wgOut, but probably did something wrong. Mediawiki PHP level is a bit above my competences ;-).

Could you help me to get the category name? I think this can help also other users with deeper analysis of websites.

--Slawek 20:26, 15 February 2016 (UTC)

Not that I like to talk to myself ;-) , but maybe someone will use the solution. In file googleAnalytics.hooks.php add:

 global $wgOut;
 $title = Title::newFromText( $wgOut->getPageTitle() );
 $categories = $title->getParentCategories();
 $category = str_replace("_"," ",str_replace("Category:","",key($categories)));

and lower, between ga(create... and ga(send... :

 ga('set', 'contentGroup1', '
 EOD
 .	$category . <<<EOD
 '); 
EOD

And create a category with index 1 in G.Analytics of course.

--Slawek 08:30, 18 February 2016 (UTC)

Outdated

This extensions is clearly outdated. I could not make it work on version 1.27.1. Instead, simply copy the relevant Google Analytics Tracking Code snippet into MediaWiki:Common.js and MediaWiki:Mobile.js (if using MobileFrontend). --Yellowdog (talk) 20:46, 8 October 2016 (UTC)Reply

New google analytics update (2018)?

Hi, the google anlaytics seem not get updated since 2015, is everything still the same now? Google analytics is using google tag, and installing the code requires pasting the tag code. How do I update to this? Thanks. — Preceding unsigned comment added by Ljianyih (talk • contribs) 02:47, 8 February 2018 (UTC)Reply

@Ljianyih: The old code (analytics.js) still works, although a major rework might be needed (there were changes in MediaWiki, too, since then). Maybe I can do this, and also follow the Google part of changes. (I have quite little experience with MediaWiki extensions, so it’s not that easy.) —Tacsipacsi (talk) 18:24, 14 February 2018 (UTC)Reply

Conformity with GDPR

In order to use Google Analytics, including using this extension, cookies or other means of user tracking is required. The GDPR law which enters into force in the EU 25th of May requires opt-in for cookies. This means usage of this extension will be illegal in the EU if not paired with an opt-in cookie prompt. There is an urgent need for an extension (or adaption of this extension) to allow this. Currently there does not seem to exist an extension solution for MediaWiki which enables such a prompt. The best I have been able to find is the MediaWiki extension “CookieWarning” but that is not good enough, since it does not offer opt-in. Input greatly appreciated.

Wrong code in instructions

While setting up this extension, I couldn't understand this code and what to include in it, and if the other site needs to have a subdomain called: analytics and a root file there called tracking.js: "https://analytics.example.com/tracking.js" I made a Google search and found no results for it,except on this page. Please correct it ASAP. Opensourceit (talk) 14:02, 14 January 2019 (UTC)Reply

That's only needed if you're using non-GA analytics alongside GA. If you are, that URL would be replaced with the appropriate URL for the analytics service you're using. If you're not, the entire line and the preceding comment can be safely deleted. 「ディノ奴千?!」☎ Dinoguy1000 15:48, 14 January 2019 (UTC)Reply