PDA

View Full Version : Google Analytics on PDF links in search results


dekortage
02-07-2007, 11:27 AM
For a client site, I installed Google Analytics to do visitor tracking. The hosting came with some tracking, but GA includes geographic analysis and site overlays that are useful to us.

If you have used GA, you know it works like this:
- You put some JavaScript code on every web page. With a template-based site, you just add it to the template and go.
- GA automatically tracks HTML links.
- If you want GA to track file downloads (such as PDFs) then you need to tag those links with an "onClick" reference to GA's code.

This is simple enough with static or CMS-driven web pages. However, PHPdig returns PDF files in its results, without tagging them for GA. Fortunately it does tag them for the "clickit()" JavaScript function, so I modified the JavaScript code to check for files in the PDF directory and call GA's code acccordingly. In the /libs/search_function.php file, look for the clickit() function around line 675, and replace it with this:

function clickit(cn,clink) {
re = /yourdomain.com%2Fpdf%2F/gi; // search for PDF reference
if (clink.search(re) != -1) {
ulink = clink.replace(re,'/pdf/');
urchinTracker(ulink); // add to Google Analytics
}
if(document.images) {
(new Image()).src=\"clickstats.php?num=\"+cn+\"&url=\"+clink+\"&val=".urlencode($js_string)."\";
}
return true;
}

Replace the text "yourdomain.com" with your actual domain name. In this example, the PDFs are always installed in a root directory called "/pdf". If your PDFs are in another directory, you will have change the "re" line and the "ulink" line appropriately.