Google Analytics Event Tracking in a Template File

Est. Reading Time: 3 minutes

Ever had an issue where you want to track unique events (or virtual pageviews) within Google Analytics from a template file?  For example, on an e-commerce site, you may have a series of product pages that use the same ‘add to cart’ button from either an include file or some kind of reusable wrapper.  You may want to track each ‘add to cart’ click as a unique event for that specific product, not just the product section as a whole.  Since the actual JavaScript snippet for event tracking can only be placed into these file once, this would seem to post a problem.

Here’s the Solution.  In this case, we are going to use the URL of each page to serve as a unique identifier for the event tracking.  If the URLs are not unique among the pages where you want the event tracked, there is a slightly more complicated solution that you can contact me on Twitter for.

In the <head> of the pages that you want tracked, place the following code snippet (or save this snippet as a JavaScript file and reference it):

<SCRIPT LANGUAGE="JavaScript">

<!--
	function passID()
	{
		var fullURL = parent.document.URL;
                var uniqueID = fullURL.substring(fullURL.indexOf('XX'),
		fullURL.indexOf('XX')+3);
		return uniqueID;
	}

//-->

</SCRIPT>

This snippet will grab a 3 character unique ID out of the page URL on which it appears.  Simply replace the XX in the code above with the 2 characters that precede the unique ID in the URL.  If the ID is only one character long, then you have it.  If it is 2 characters, replace the “+3″ above with “+4″.  If it is 3 characters, replace the “+3″ with “+5″, and so forth.

Note: If XX appears multiple times in URL, you will want to make it longer than two characters to ensure that you get the identifier that you want.  Just make sure to adjust the ending portion of the substring accordingly.

Now that we have our unique ID, the rest of the event tracking is easy.  For your onClick or onSubmit event, the tracking code for GA usually appears as:

_gaq.push(['_trackEvent', 'Category', 'Action', 'Label']);

With ‘Category’, ‘Action’, and ‘Label’ each being strings that the coder enters to display in Analytics.

In this case, we’re just going to make one adjustment:

_gaq.push(['_trackEvent', 'Category', 'Action', passID()]);

‘Label’ has been replaced by passID(), the function we created in the <head> of the page for the uniqueID.  You could also replace ‘Category’ or ‘Action’ with the passID() function as well, but I think ‘Label’ makes the most sense as these pages are going to be similar in nature coming from the same template file.

That’s it, the unique ID will now show in the label section of GA.  Feel free to contact me with any questions and I’d love to hear about any case studies where you use this.

- EJW, follow me on twitter: @ejwestksu