Track file downloads with Google Analytics

Adding a web statistic package of the Google Analytics or Piwik likes to a Textpattern-powered site is no big deal: The stats package hands you a tiny JavaScript snippet for inclusion in the site’s page templates. Alas, this snippet will only track HTML resources, while downloadable files stay below its radar: Google Analytics needs an explicit trigger to grab clicks on downloadable files’ links.

A visitor’s browser will do so with the help of a short jQuery script.

Add jQuery to your site

I prefer to have all scripts in a separate folder, conveniently named scripts:

<script type="text/javascript" src="<txp:site_url />scripts/jquery-1.3.2.min.js"></script>

Move Google Analytics to the page top

For performance reasons, Google commonly suggests to keep the tracking script at the very end of a page. To get file tracking working, the tracking script has to be placed rather early in your page near the closing </head> tag.

Add download tracking

Add the actual download tracking code at any convenient page template location. This snippet watches out for clicks onto links matching a http://www.example.com/file_download/nnn/name.ext pattern and feeds their URL into Google Analytics:

<script type="text/javascript">
$(document).ready(function(){
 $('a[href*=file_download]').click(function(){
  try {
   var p = this.href.match(/http:\/\/[-a-zA-Z0-9\.]*(\/file_download\/[0-9]*\/.*)/)[1];
   pageTracker._trackPageview(p);
  } catch(err) {}
 })
})
</script>

Wait a few hours and watch downloads appear at your site’s content report.

(Diesen Artikel gibt es auch in Deutsch: Dateidownloads aus Textpattern mit Google Analytics verfolgen)

comments powered by Disqus