Future Proofing Your Google Analytics Code for Tracking PDFs

A few years back I started using Google Analytics to get a better idea of what people are viewing on our websites. To be prepared for future revisions of the tracking code, I thought all I needed to do was store the code in a file called "GoogleAnalytics.html" and import it into the pages we wanted to track. Then as Google releases new versions of the tracking code, I would only need to update the GoogleAnalytic.html file for each website.

Background

Unfortunately, you can't add the tracking code to every file on the website. To track how many visitors open a PDF for example, you have to add extra code to the page that links to the PDF. Let's say you wanted to link to the Spring 2010 newsletter. The tracking code would likely be added to the anchor tag using the "onclick" attribute as follows:

<a href="/newsletter/2010spr.pdf" onclick="javascript:urchinTracker('/newsletter/2010spr.pdf');">Spring 2010 Newsletter</a>

The problem was that I didn't think about future proofing this part of the tracking code. So when the time arrived to update the analytics code, I needed to replace more than 230 onclick references throughout one website.

So instead of hard-coding the onclick attribute like before, I wanted to create a PHP function that writes the tracking code for me. In addition to being able to create tracking code for PDFs, Word documents, PowerPoint files, etc., the function should be able to handle links to other websites.

Building the Function

First I defined a PHP function called "addTrackingCode". The function accepts one argument ($link) which is used to send the link to track.

<?php
//FUNCTION USED TO ADD TRACKING CODE TO DOWNLOADABLE FILES (SUCH AS PDFs) AND TO EXTERNAL WEBSITE LINKS
function addTrackingCode($link) {
}
?>

Inside the function, I prepare the link for Google Analytics.

<?php
//FUNCTION USED TO ADD TRACKING CODE TO DOWNLOADABLE FILES (SUCH AS PDFs) AND TO EXTERNAL WEBSITE LINKS
function addTrackingCode($link) {
     //IF THE LINK LEADS TO MY WEBSITE (http://www.mywebsite.com/newsletter/2010spr.pdf), REMOVE THE "http://" AND THE DOMAIN NAME
     if(substr($link, 0, 24)=='http://www.mywebsite.com') {
          $link = substr($link, 24);
          
     //ELSE...IF THE LINK STARTS WITH "http", IT'S AN EXTERNAL LINK
     } elseif(substr($link, 0, 4)=='http') {
          //IF THE LINK STARTS WITH "https://", REMOVE IT
          if(substr($link, 0, 8)=='https://')  {
               $link = substr($link, 8);
          
          //ELSE...IF THE LINK STARTS WITH "http://", REMOVE IT
          } elseif(substr($link, 0, 7)=='http://') {
               $link = substr($link, 7);
          }
          
          //ADD "/external/" TO THE BEGINNING OF THE LINK SO THAT ALL THE EXTERNAL LINKS ARE GROUPED INTO THE SAME FOLDER IN GOOGLE ANALYTICS
          $link = '/external/' . $link;
     
     //ELSE...IF THE LINK DOESN'T LEAD WITH A SLASH, ADD ONE (note that if the link doesn't begin with a slash, Google Analytics groups it under a folder labeled "/../")
     } elseif(substr($link, 0, 1) != '/') {
          $link = '/' . $link;
     }
}
?>

Then an "onclick" attribute containing the tracking code for the formatted link is returned.

<?php
//...
 
     } elseif(substr($link, 0, 1) != '/') {
          $link = '/' . $link;
     }
    
     //RETURN THE FORMATTED LINK
     return " onclick=\"javascript:urchinTracker('$link');\"";

}
?>

Where Does the Function Go?

Since the standard Google Analytics code is already being imported, I added the function to the "GoogleAnalytics.html" page:

<?php
//STANDARD GOOGLE ANALYTICS TRACKING CODE (note that the "UA-XXXXXXX-X" needs to be replaced with your tracking code ID)
?>
<script src="http://www.google-analytics.com/urchin.js" type="text/javascript">
</script>
<script type="text/javascript">
_uacct = "UA-XXXXXXX-X";
urchinTracker();
</script>
<?php
//FUNCTION USED TO ADD TRACKING CODE TO DOWNLOADABLE FILES (SUCH AS PDFs) AND TO EXTERNAL WEBSITE LINKS
function addTrackingCode($link) {
     //IF THE LINK LEADS TO MY WEBSITE (http://www.mywebsite.com/newsletter/2010spr.pdf), REMOVE THE "http://" AND THE DOMAIN NAME
     if(substr($link, 0, 24)=='http://www.mywebsite.com') {
          $link = substr($link, 24);
          
     //ELSE...IF THE LINK STARTS WITH "http", IT'S AN EXTERNAL LINK
     } elseif(substr($link, 0, 4)=='http') {
          //IF THE LINK STARTS WITH "https://", REMOVE IT
          if(substr($link, 0, 8)=='https://')  {
               $link = substr($link, 8);
          
          //ELSE...IF THE LINK STARTS WITH "http://", REMOVE IT
          } elseif(substr($link, 0, 7)=='http://') {
               $link = substr($link, 7);
          }
          
          //ADD "/external/" TO THE BEGINNING OF THE LINK SO THAT ALL THE EXTERNAL LINKS ARE GROUPED INTO THE SAME FOLDER IN GOOGLE ANALYTICS
          $link = '/external/' . $link;
     
     //ELSE...IF THE LINK DOESN'T LEAD WITH A SLASH, ADD ONE (note that if the link doesn't begin with a slash, Google Analytics groups it under a folder labeled "/../")
     } elseif(substr($link, 0, 1) != '/') {
          $link = '/' . $link;
     }
    
     //RETURN THE FORMATTED LINK
     return " onclick=\"javascript:urchinTracker('$link');\"";
}
?>

Using the Function

Now that the function is imported along with the standard Google Analytics code, it can be used when linking to things like PDFs. Instead of hard coding the onclick attribute like earlier:

<a href="/newsletter/2010spr.pdf" onclick="javascript:urchinTracker('/newsletter/2010spr.pdf');">Spring 2010 Newsletter</a>

We can utilize the new function:

<a href="/newsletter/2010spr.pdf"<?php print addTrackingCode('/newsletter/2010spr.pdf'); ?>">Spring 2010 Newsletter</a>

Updating the Analytics Code

With the Google-specific tracking code located in one place (GoogleAnalytics.html), it can be quickly modified as new versions are released. We just need to replace the standard tracking code and the return statement at the end. The code below shows the newest tracking code provided by Google:

<?php
//STANDARD GOOGLE ANALYTICS TRACKING CODE (note that the "UA-XXXXXXX-X" needs to be replaced with your tracking code ID)
?>
<script type="text/javascript">
  var _gaq = _gaq || [];
  _gaq.push(['_setAccount', 'UA-XXXXXXX-X']);
  _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>
<?php
//FUNCTION USED TO ADD TRACKING CODE TO DOWNLOADABLE FILES (SUCH AS PDFs) AND TO EXTERNAL WEBSITE LINKS
function addTrackingCode($link) {
     //...prepare link here
 
     //RETURN THE FORMATTED LINK
     return " onclick=\"javascript:_gaq.push(['_trackPageview', '$link']);\"";
}
?>

Feedback

Do you use Google Analytics to track visits to external websites from your website? If so, do you do anything special to group those visits together? Also, don't hesitate to ask if you have any questions about the analytics function or if you have suggestions.

Related Resources

  • PHP.net – the online PHP manual which is helpful for finding out more information on the PHP substr() function for example
  • Google Analytics Help – the help section for Google Analytics which may be able to answer your questions about the service

Related Posts

0 Comments

There are currently no comments.

Leave a Comment