Path Analysis in Google Analytics using event tracking and custom cookies
I’ve had a lot of people ask me about page pathing; what order a certain set of pages have been viewed in or which pages are typically viewed before a visitor gets to a specific page on a website. When they do, I usually point them in the direction of the behavour flow report, below.
My problem with this report is that it is more focussed at showing which pages were viewed at a specific interaction number. So if I want to see what visitors are doing after seeing /whatido/ page in their first interaction then that’s fine, but what if actually /whatido/ was more commonly a 5th or 6th interaction it gets messy very quickly.
There is obviously no easy solution to this, as whatever solution you create is going to show you thousands of different paths through your site and no one is going to sit and analyse all that data.
The solution I’m proposing uses a combination of event tracking and custom cookies that tells us which page the visitor is on, how many times they have visited that page and what interaction number this page view is. So, for example you would be able to see that the first time a visitor hits your product page is their fourth interaction on the site.
Custom page pathing:
We start by defining two functions, taken from http://www.quirksmode.org/js/cookies.html which will allow us to quickly read and write cookies to the users computer.
We then create a variable containing the name of our first cookie = ‘pagetotal:’ + window.location.pathname; for my homepage this would be: pagetotal:/.
We then check to see if this cookie already exists (the visitor has been to the homepage before) and if it does then we add one to the length of the cookie, increasing the page count for the homepage by 1. If not then we create the cookie telling us that the visitor is on the homepage for the first time.
Next, we need to find out what interaction number this is, so we check to see if our next cookie exists, in my code called ‘pathrank’. If it exists then we increase the count for this cookie by one, giving us the current interaction number and we fire an event to Google Analytics capturing the page, the page count and the interaction number.
If it doesn’t then we create the cookie and fire the same event but the interaction count is set to 1.
In my code I have also captured the visitor ID by reading the __utma google analytics cookie and have set this as the event action. This allows me to view individual visitor page pathing as well as the wider picture. It also means that if I passed that Visitor ID to my CRM database I would be able to tie back specific visitor journeys that have resulted in a conversion or entry into the database.
Finally, the whole script is wrapped in a $(window).load function so that the google analytics cookies have chance to set before the script executes and tries to read them.
You can download the code here and let me know what you think.