[ index ]

Adding the Tracking Code for Google Analytics

Do you need to add the tracking code block to every webpage on your site? Depending on the nature of your site and the tools you use to publish webpages this can be as simple as filling in the blank in one form or as daunting as the prospect of editing every single file the site. My site has been around for a while and over the years I have used a variety of techniques to publish pages depending on my current skill level at the time. So in my case adding tracking code to every page ranges from dealing with plain html pages written with vi to the results of content generating techniques based on lMaker, mySQL or php.

For this example we imagine the worst case, a site of plain html files that have to be handled individually and we have to insert that snippet of tracking code into each file just before the </head> tag. The plan is to use the find command to walk us through the website one file at a time and then use the ed command to insert our code where we want it to appear.

In the top level directory of the website we need to make three small files to help us out. First we copy our tracking code into a file:

Note that you need to replace the UA-######-1 with your own website's tracking code.

Next we will need a set of instructions for ed:

Those four little lines will save us a lot of work. The line /<\/HEAD> tells ed to go the first occurence of a line containing the closing </head> tag. (That is a case-sensitive search so if you need to, change it to /<\/head> instead.) The next line, -1r tracking.txt tells ed to read and insert the contents of tracking.txt above the current line. The 'w' command writes out the file and 'q' is for 'quit'.

Finally we need a shell script to pull it all together for us:

At the Unix command prompt enter "sh install_tracking.sh". That's what I did and now my site is ready to reap the benefits of all those cool reports available from Google Analytics.

2006-04-05 16:03:21
FREE CONTENT: The articles published here are available for public use on websites that abide by the current Google AdSense publishing policies with the provision that a visible and unfettered link back to the original article here must be included immediately following the republished material.

©2008 Echo3 Online Services, LLC