Google Analytics file tracking

iaian7 » code » txp   John Einselen, 3.06.07 (updated 7.02.17)    

Update: this is pretty outdated as Google has changed Analytics setup and formatting over the years. It’s left here for reference, in case you’re interested in customising text processing.

Google Analytics is great at tracking visitors, but file downloads aren’t included in site traffic reports since files links (and links to places outside your site) don’t include the necessary javascript. This hack will change the default function of Textile’s "link(title)":url into a Google Analytics urchin tracker, allowing you to easily add file downloads and external link tracking to your Analytics reports.

Note: this changes the default behavior of the Textile link formating, so any use of the (title) format will be updated from title="" to an Analytics tracked link.

Find the following file and open it in an editor (TextWrangler is excellent).

/textpattern/lib/classTextile.php

Once open, navigate to line 735 and you’ll find (all on one line):

$atts .= ($title != '') ? ' title="' . $this->encode_html($title) . '"' : '';

Change it to read something like this (all one line):

$atts .= ($title != '') ? ' onclick="javascript:urchinTracker (\'/downloads/' . $this->encode_html($title) . '\'); "' : '';

It’s probably a good idea to either backup your original classTextile.php file, or leave a commented copy of the original code (// $atts...) in case something goes sour. Feel free to change downloads/ to any sudo-folder for organization in the Analytics report, or remove it and include the sudo-path in your Textile formatting for each link ("link(downloads/title)":url). If you change the code from what’s listed above, make sure any apostrophes are properly escaped with a backslash (\').

Save the file (uploading it if you downloaded to edit), and you’re done. Creating links with "link(title)":url will now track /downloads/title in your Google reports. The Google Analytics code does need to come before any links on the page, so if you’ve included the Analytics script at the bottom of your page, it’ll need to move to the top (still within the <body> tag, of course).

Articles are parsed when they are saved in Textpattern, not when served to a visitor! If you change your textile file, you’ll need to re-save affected articles to refresh the output.

If you prefer, you can just download the already hacked file here: classTextile.zip

bookmark