Piwik: Tracking User Interactions

Exclusive offer: get 50% off this eBook here
Piwik Web Analytics Essentials

Piwik Web Analytics Essentials — Save 50%

A complete guide to tracking visitors on your websites, e-commerce shopping carts, and apps using Piwik Web Analytics with this book and ebook.

$26.99    $13.50
by Stephan A. Miller | October 2012 | e-Commerce Open Source

Despite the advanced tracking features of Piwik, there are still some actions on a website that may require you to do some manual work in order to track. Events in JavaScript and Flash don't cause a page load and because of that, the standard Piwik tracking code won't register any details other than a visit. In order to record user interactions with website elements such as Flash, Ajax, JavaScript, and third-party widgets, you need to use different tactics.

In this article by Stephan A. Miller, author of Piwik Web Analytics Essentials, we will learn:

  • What event tacking is used for
  • How to set up event tracking in Piwik using custom variables
  • How to track social media events on your website
  • How to track blog commenting events
  • How to track e-commerce events
  • How to track Flash events in either ActionScript 2 or ActionScript 3

Tracking events with Piwik

Many of you may be familiar with event tracking with Google Analytics; and many of you may not. In Google Analytics, event tracking is pretty structured. When you track an event with Google, you get five parameters:

  • Category: The name for the group of objects you want to track
  • Action: A string that is used to define the user in action for the category of object
  • Label: This is optional and is for additional data
  • Value: This is optional and is used for providing addition numerical data
  • Non-interaction: This is optional and will not add the event hit into bounce rate calculation if set to true

We are going over a few details on event tracking with Google Analytics because the custom variable feature we will be using for event tracking in Piwik is a little less structured. And a little structure will help you drill down the details of your data more effectively from the start. You won't have to restructure and change your naming conventions later on and lose all of your historical data in the process. We don't need to look over the code for Google Analytics. Just know that it may help to set up your event tracking with a similar structure.

If you had videos on your site, enough to track, you would most likely make a category of events Videos. You can create as many as you need for the various objects you want to track on your site:

  • Videos
  • Maps
  • Games
  • Ads
  • Blog posts (social media actions)
  • Products

As for the actions that can be performed on those Videos, I can think of a few:

  • Play
  • Pause
  • Stop
  • Tweet
  • Like
  • Download

There are probably more than you can think of, but now that we have these actions we can connect them with elements of the site. As for the label parameter, you would probably want to use that to store the title of the movie the visitor is interacting with or the page it is located on. We will skip the value parameter which is for numeric data because with Piwik, you won't have a similar value. But non-interaction is interesting; it means that by default an action on a page counts to lower the bounce rate from that page since the user is doing something. Unfortunately, this is not a feature that we have using Piwik currently, although that could change in the future.

Okay, now that we have learned one of the ways to structure our events, let's look at the way we can track events in Piwik. There is really nothing called event tracking in Piwik, but Piwik does have custom variables which will do the same job. But, since it is not really event tracking in the truest sense of the word, the bounce rate will be unaffected by any of the custom variables collected. In other words, unlike Google Analytics, you don't get the non-interaction parameter you can set. But let's see what you can do with Piwik.

Custom variables are name-value pairs that you can set in Piwik. You can assign up to five custom variables for each visitor and/or each page view. The function for setting a custom variable is setCustomVariable . You must call it for each custom variable you set up to the limit of five.

piwikTracker.setCustomVariable (index, name, value, scope);

And here are what you set the parameters to:

  • index: This is a number from 1 to 5 where your custom variables are stored. It should stay the same as the name of custom variable. Changing the index of a name later will reset all old data.
  • name: This is the custom variable name or key.
  • value: This is the value for name.
  • scope: This parameter sets the scope of the custom variable, whether it is being tracked per visit or per page. And what scope we set depends upon what we are tracking and how complex our site is.

So how do these custom variables fit our model of event tracking? Well we have to do things a little bit differently. For most of our event tracking, we will have to set our variable scope per page. There is not enough room to store much data at the visit level. That is good for other custom tracking you may need but for event tracking you will need more space for data.

So with page level custom variables, you get five name-value sets per page. So, we would set up our variables similar to something like this for a video on the page:

  • Index = 1
  • Name = "Video"
  • Value = "Play","Pause","Stop","Tweet","Like", and so on
  • Scope = "page"

And this set of variables in using Piwik's custom variable function would look like one of the following:

  • piwikTracker.setCustomVariable(1,"Video","Play","page");
  • piwikTracker.setCustomVariable(1,"Video","Pause","page");
  • piwikTracker.setCustomVariable(1,"Video","Tweet","page");

Which one you would use would depend on what action you are tracking. You would use JavaScript in the page to trigger these variables to be set, most likely by using an onClick event on the button. We will go into the details of various event tracking scenarios later in this chapter.

You will notice in the previous snippets of code that the index value of each call is 1. We have set the index of the "Video" name to 1 and must stick to this now on the page or data could be overwritten. This also leaves us the two to five indexes still available for use on the same page.

That means if we have banner ads on the page, we could use one of the spare indexes to track the ads.

piwikTracker.setCustomVariable(2,"SidebarBanner","Click","page");

You will notice that Google event tracking has the label variable. As we are using page leveling custom variables with Piwik and the variables will be attached to the page itself, there is no need to have this extra variable in most cases. If we do need to add extra data other than an action value, we will have to concatenate our data to the action and use the combined value in Piwik's custom tracking's value variable. Most likely, if we have one banner on our video page, we will have more and to track those click events per banner, we may have to get a little creative using the following:

  • piwikTracker.setCustomVariable(2,"SidebarBanner", "AddSlot1Click","page");
  • piwikTracker.setCustomVariable(2,"SidebarBanner", "AddSlot2Click","page");
  • piwikTracker.setCustomVariable(2,"SidebarBanner", "AddSlot3Click","page");

Of course, it is up to you whether you join your data together by using CamelCase, which means joining each piece of data together after capitalizing each. This is what I did previously. You can also use spaces or underscores as long as it is understandable to you and you stick to it. Since the name and value are in quotation marks, you can use any suitable string.

And again, since these are custom variables, if you come up with a better system of setting up your event tracking that works better with your website and business model, then by all means try it. Whatever works best for you and your site is better in the long run.

So now that we have a general idea of how we will be tracking events with Piwik, let's look at some specific examples and more in depth at what events are, compared to goals or page views.

Tracking social engagement

You know that you have a Facebook "Like" button on your page, a Twitter "tweet" button, and possibly lots more buttons that do various things at other sites that you yourself have no control over and can add no tracking code to. But you can track clicks on the button itself.

You use event tracking for what you could call micro-conversions. But there is really nothing micro about them. That Facebook "Like" could end up in many more sales or conversions than a standard conversion. They could be the route on the way to one or multiple conversions. There may be a blurry line between engagement goals and micro-conversions.

And really, it is up to you what weight you give to visitor actions on your site, but use events for something smaller than you would consider a goal. If your goal is sales on your website, that Facebook "Like" should cause a spike in your sales and you will be able to correlate that to your event tracking, but the "Like" is not the end of the road, or the goal. It is a stop on the way.

If your website is a blog and your goal is to promote advertising or your services with your content, then tracking social engagement can tell you which topics have the highest social interest so that you can create similar content in the future.

So what are some other events we can track? Of course, you would want to track anything having to do with liking, tweeting, bookmarking, or somehow spreading your site on a social network. That includes Facebook , Twitter , Digg , StumbleUpon , Pinterest , and any other social network whose button you put on your site. If you spent enough time to put the buttons on your pages, you can at least track these events. And if you don't have buttons, you have to remember that each generation is using the Internet more often; smartphones make it available everywhere, and everyone is on a social network. Get with it.

And don't forget to add event tracking to any sort of Follow Me or Subscribe button. That too is an event worth tracking.

We will also look at blog comments since we can consider them to be in the social realm of our tracking.

Tracking content sharing

So let's look at a set of social sharing buttons on our website. We aren't going to blow things out of proportion by using buttons for every social network out there, just two: Twitter and Facebook. Your site may have less and should have more, but the same methods we will explore next can be used for any amount of content sharing buttons.

We are event tracking, so let's begin by defining what our custom variable data will be. We need to figure out how we are going to set up our categories of events and the actions. In this example, we will be using buttons on our Holy Hand Grenade site:

You will see our Twitter button and our Facebook button right underneath the image of our Holy Hand Grenade.

We are going to act as if our site has many more pages and events to track on it and use a naming convention that will leave room for growth. So we are going to use the category of product shares. That way we have room for video shares when we finally get that cinematographer and film our Holy Hand Grenade in action.

Now we need to define our actions. We will be adding more buttons later after we test the effectiveness of our Facebook and Twitter buttons. This means we need a separate action to distinguish each social channel.

  • Share on Facebook
  • Share on Twitter

And then we add more buttons:

  • Share on Google+
  • Share on Digg
  • Share on Reddit
  • Share on StumbleUpon

So let's look at the buttons in the source of the page for a minute to see what we are working with:

<li class="span1">
<script type="text/javascript" src='//dgdsbygo8mp3h.cloudfront.net/sites/default/files/blank.gif' data-original="http://platform.twitter.
com/widgets.js"></script>
<a href="https://twitter.com/intent/
tweet?url=http%3A%2F%2Fdir23.com&text=Holy%20Hand%20Grenades"
class="twitter-share-button">Tweet</a>
</li>

<li class="span1"></li>

<li class="span1">
<script src='//dgdsbygo8mp3h.cloudfront.net/sites/default/files/blank.gif' data-original="http://connect.facebook.net/en_US/all.
js#xfbml=1"></script>
<fb:like href="http://dir23.com/" show_faces="false"
width="50" font=""></fb:like>
</li>

</ul>

<p><a class="btn btn-primary btn-large">Buy Now >></a></p>

You see that the buttons are not really buttons yet, they are only HTML anchors in the code and JavaScript includes. Before we start looking at the code to track clicks on these buttons, we need to go over some details about the way Piwik's JavaScript works. Setting a custom variable in Piwik using an onclick event is a very tricky procedure. To start with, you must call more than just setCustomVariable because that will not work after the Piwik tracking JavaScript has loaded and trackPageView has been called. But there is a way around this. First, you call setCustomVariable and then, in that same onclick event , you call trackLink , as in the next example:

<p><a href="buynow.html" class="btn btn-primary btn-large" onclick="
javascript:piwikTracker.setCustomVariable(2,'Product Pricing','View
Product Price','page');piwikTracker.trackLink();">Buy Now >></a></p>

If you forget to add the piwikTracker.trackLink() call, nothing will happen and no custom variables will be set.

Now with the sharing buttons, we have another issue when it comes to tracking clicks. Most of these buttons, including Facebook, Twitter, and Google+ use JavaScript to create an iframe that has the button. This is a problem, because the iframe is on another domain and there is not an easy way to track clicks.

For this reason, I suggest using your social network's API functionality to create the button so that you can create a callback that will fire when someone likes or tweets your page. Another advantage to this method is that you will be sure that each tracked tweet or like will be logged accurately. Using an on_click event will cause a custom variable to be created with every click. If the person is not logged in to their social account at the time, the actual tweet or like will not happen until after they log in, even if they decide to do so. Facebook, Twitter, and Google+ all have APIs with this functionality.

But if you decide to try to track the click on the iframe, you can take a look at the code at http://www.bennadel.com/blog/1752-Tracking-Google-AdSense- Clicks-With-jQuery-And-ColdFusion.htm to see how complicated it can get. The click is not really tracked. The blur on the page is tracked, because blur usually happens if a link in the iframe is clicked and a new page is about to load.

We already have our standard Piwik tracking code on the page. This does not have to be modified in any way for event tracking. Instead we will be latching into Twitters and Facebook's APIs which we loaded in the page by including their JavaScript.

<script>
twttr.events.bind('tweet', function(event) {
piwikTracker.setCustomVariable(1,'Product Shares','Share on
Twitter','page');
piwikTracker.trackLink();
});
</script>

<script type="text/javascript">
FB.Event.subscribe('edge.create', function(response) {
piwikTracker.setCustomVariable(1,'Product Shares','Share on
Facebook','page');
piwikTracker.trackLink();
});
</script>

We add these two simple scripts to the bottom of the page. I put them right before the Piwik tracking code. The first script binds to the tweet event in Twitter's API and once that event fires, our Piwik code executes and sets our custom variable. Notice that here too we have to call trackLink right afterwards. The second script does the same thing when someone likes the page on Facebook.

It is beyond the scope of this book to go into more details about social APIs, but this code will get you started and you can do more research on your chosen social network's API on your own to see what type of event tracking will be possible. For example, with the Twitter API you can bind a function to each one of these actions: click, tweet, retweet, favorite, or follow. There are definitely more possibilities with this than there is with a simple onclick event.

Using event tracking on your social sharing buttons will let you know where people share your line of Holy Hand Grenades. This will help you figure out just which social networks you should have a presence on. If people on Twitter like the grenades, then you should make sure to keep your Twitter account active, and if you don't have a Twitter account and your product is going viral there, you need to get one quick and participate in the conversation about your product.

Or you may want to invest in the development of a Facebook app and you are not quite sure that it is worth the investment. Well, a little bit of event tracking will tell you if you have enough people interested in your website or products to fork over the money for an app.

Or maybe a person goes down deep into the pages of your site, digs out a gem, and it gets passed around StumbleUpon like crazy. This might indicate a page that you should feature on the home page of your website. And if it's a product page that's been hidden from light for years, maybe throw some advertising its way too.

Piwik Web Analytics Essentials A complete guide to tracking visitors on your websites, e-commerce shopping carts, and apps using Piwik Web Analytics with this book and ebook.
Published: October 2012
eBook Price: $26.99
Book Price: $44.99
See more
Select your format and quantity:

Tracking blog comments

Commenting is a useful way to get feedback on your content and it is a feature that is built into every blogging platform. By adding a blog to your business site you can turn it into a community instead of a static business card, and adding a blog to an e-commerce website will add a useful knowledge base to what was only a showroom.

Comments are definitely something you should track with analytics. The data you receive will tell you which content engages your visitors the most. More people will bookmark, tweet, or share content than comment, because it is simply easier. So when you find a story that gets a reaction from your audience, you can focus on topics that are most likely to get comments instead of those that have not received much interaction in the past.

Now you could make commenting a goal, but this could give you a lot of goals as your content increases. It would be better to track comments as events. Your goal is to actually grow a community over time. You also could just use the actual comment count from the admin panel of your blogging platform, but it is much easier to consolidate this data in Piwik than to have to refer to more than one application for your analytics data.

So let's look at how we are going to set up the custom variables to track our blog comment events. Again, we can think in terms of categories and actions. But with comments, this is pretty simple. We could simply call our category "Blog Comments" and the action "Submit Comment". And since we will be using page level scope, we will be able to correlate these comments directly to the content they occurred on.

So the snippet of code that will be tracking these comments will look like the following:

piwikTracker.setCustomVariable(1,"Blog Comments","Submit
Comment","page");
piwikTracker.trackLink();

Here is an example of a comment form on a WordPress blog, mine in fact:

This will be simple. Again, we will be attaching our setCustomVariable function to the onclick event of a button. This time it is the comment submit button we will be using (the button that says Post Comment). Here is the section of the page that has the button before we add our event tracking code.

<p class="form-submit">
<input name="submit" class="sm-button" type="submit" id="submit"
value="Post Comment">
<input type='hidden' name='comment_post_ID' value='1653'
id='comment_post_ID'>
<input type='hidden' name='comment_parent' id='comment_parent'
value='0'>
</p>

We already have the parameters that we will be using and I am assuming the Piwik tracking code is in place. So all we have to do is insert our onclick event:

<p class="form-submit">
<input name="submit" class="sm-button" type="submit"
id="submit" value="Post Comment" onclick="javascript:
piwikTracker.setCustomVariable(3,'Blog Comments','Submit
Comment','page');piwikTracker.trackLink();">
<input type='hidden' name='comment_post_ID' value='1653'
id='comment_post_ID'>
<input type='hidden' name='comment_parent' id='comment_parent'
value='0'>
</p>

Now, we will track a new blog comment every time someone clicks this button. This may be what we want to get started, but if your blog gets a lot of comment spam, this may not be the best way to do things. In the following screenshot of my WordPress admin, I currently get about 20 percent spam that my spam filtering plugin catches. And still, there will be a lot of spam in the comments that make it past this filter.

Instead of tracking with the comment submission button, it would be better in this case to track events when the comments are approved. This will involve more complex coding and would probably be best done with a plugin for your blogging platform. It is never a good practice to hack the core files of your blogging platform. For example, in WordPress , you would have to be sure to track a comment event when a comment is approved one by one, and multiple events when comments are approved in bulk. This will require more than simple JavaScript. You will have to get out your PHP programming skills.

Tracking e-commerce events

To continue with the road analogy, the road to an online purchase has many twists and forks and stops along the way. The end goal, of course, is the sale. A customer could view instructions on how to use a product, add the product to the cart, and make in to the checkout page. Each one of these steps is an event along the route that leads to a sale.

You will notice on our Holy Hand Grenade site that no price is listed on the product page; there is just a Buy Now button.

When someone clicks that button, they are interested in buying. They aren't buying yet, but they are at least curious about the price. Not yet a goal, but an event we want to track.

By tracking this event, we can find out what percentages of our visitors are checking out the price as well as the percentage who finally converted. If the percentage who clicked the button is high, our landing page is good. If it is lower, we can split test it with a new version, but it is good to test periodically either way to increase this click-through percentage. And if our goal conversion rate is a little low, we can play around with the price of our hand grenade or maybe experiment with making our checkout page a little less complicated.

So let's set up our custom variables to track people who check out the price of our Holy Hand Grenade. In other words, who makes it from the page (shown in the previous screenshot) and is interested enough to click the Buy Now button and make it to the following page:

So to track this event, we are going to use a category of "Product Pricing" and an action of "View Product Price" and our snippet of JavaScript will look something like the following:

piwikTracker.setCustomVariable(1,"Product Pricing","View Product
Price","page");
piwikTracker.trackLink();

And again, we will use our handy onclick JavaScript event to trigger this Piwik code. Here is our button code before adding event tracking:

<p><a href="buynow.html" class="btn btn-primary btn-large">Buy Now
>></a></p>

And after we add our onclick event:

<p><a href="buynow.html" class="btn btn-primary btn-large" onclick="
javascript:piwikTracker.setCustomVariable(1,'Product Pricing','View
Product Price','page'); piwikTracker.trackLink();">Buy Now >></a></p>

This will tell us how many people have clicked through to see the price of our product.

If we had a full e-commerce website with hundreds or even thousands of products for sale, it would be a good idea to concatenate the product category to the action. In the previous example, we would do this if our holy hand grenade were in a 'Gold Things' category.

piwikTracker.setCustomVariable(1,'Product Pricing','Gold Things-View
Product Price','page');

When you have thousands of products, it is good to know the best performing categories of your store. Finding top performing products is easy, especially with e-commerce tracking.

There are many other events you may want to track if you own an e-commerce website. Here are a few:

  • Social media buttons
  • Request a quote forms
  • Save shopping cart notices
  • Trial software downloads
  • Video demonstrations of a product
  • Related, upsell, or cross-sell products
  • Live chat links
  • Newsletter sign ups
  • Adding a product review
  • Posting a question to a forum

Which events you decide to track depends on what features you have on your website and what actions are important on the road to your goals.

Tracking Flash events

You have to give it to Flash. It has stuck around for a long time. Even when JavaScript can now do most of the interactive effects on the page, Flash is still useful when it is used in the right places. One thing Flash works well with is movies, and with movies you'll want to track plays, pauses, and stops among other things as events.

We won't go deep into Flash here, just point you in the right direction if you know enough Flash to edit ActionScript. First, you need to know what version of ActionScript you are using, either ActionScript 2 or ActionScript 3.

Tracking events with ActionScript 2

We are going to make this simple. We are only going to embed an SWF movie file into a web page with a play button, and we are going to only track clicks on this play button as an event. In this same web page, you will have your standard Piwik tracking code already in place.

In ActionScript 2, we will have to use the getURL method to set the custom variables we will be using to track the play events. So in your Flash application, you will want to put this code in so that an event is tracked:

on (release) {
getURL ("javascript:(function(){piwikTracker.setCustomVariable
(1,"Video","Play","page");})()");
}

You will notice that we wrapped the Piwik function call in another anonymous JavaScript function and added an extra set of brackets at the end of this function. Doing this will cause the setCustomVariable function to execute immediately. There is no onclick event to attach to in Flash. We have to give it a little help to get the job done.

Tracking events with ActionScript 3

Okay, now with the ActionScript 3 example we are going to assume we are doing the same thing as done previously, but with ActionScript 3 code. This takes a little bit more code writing.

First, you have to reference external classes in your FLA file.

import flash.external.ExternalInterface

Then you will add an event listener to the play button in your FLA file. You will be using this ExternalInterface to communicate with the Piwik tracking code already in the page the video is located.

playBtn.addEventListener(
MouseEvent.CLICK, ExternalInterface.call('piwikTracker.
setCustomVariable', 1,'Video', 'Play', 'page'));

Then in the SWF embed code, you will have to allow all of this to happen by setting allowScriptAccess to always in two locations.

<object ...
<param name="allowScriptAccess" value="always" />
<!-- {THE_REST_OF_THE_OBJECT_HERE} -->
<embed ...
allowScriptAccess="always"
<!-- {THE_REST_OF_THE_EMBED_HERE} -->
</embed>
</object>

If you know Flash and ActionScript, this should be a pretty simple addition to your code. You can use similar code to call other methods in the piwikTracker object .

Summary

In this article we learnt how to use Piwik's custom variable feature for event tracking and used it to track social media events, blog comments, e-commerce events, and Flash events.

Piwik Web Analytics Essentials A complete guide to tracking visitors on your websites, e-commerce shopping carts, and apps using Piwik Web Analytics with this book and ebook.
Published: October 2012
eBook Price: $26.99
Book Price: $44.99
See more
Select your format and quantity:

About the Author :


Stephan A. Miller

Stephan A. Miller is a web and app developer, SEO expert, and blogger who lives in Kansas City, Missouri. He was head developer at All About Doors and Windows in Kansas City for six years and was a freelance developer and SEO expert for eight years.

In his career, he has worked with Wordpress, Drupal, Magento, osCommerce, ZenCart, and many other online applications, as well as developing sites from scratch in PHP and MySQL or using the Lithium PHP framework. But this is not all. Because his business was at times a one man show, he knows Linux, Apache, and Nginx well and has developed desktop applications in Python where PHP just won't work. He also knows search engine optimization techniques, web analytics software, and search engine marketing which he uses to promote his own handful of sites. He blogs semi-regularly at http://www.stephanmiller.com about his work.

Books From Packt


PHP 5 E-commerce Development
PHP 5 E-commerce Development

Django 1.2 E-commerce
Django 1.2 E-commerce

WordPress 2.9 E-Commerce
WordPress 2.9 E-Commerce

Drupal E-commerce with Ubercart 2.x
Drupal E-commerce with Ubercart 2.x

Selling Online with Drupal e-Commerce
Selling Online with Drupal e-Commerce

TYPO3 4.2 E-Commerce
TYPO3 4.2 E-Commerce

PrestaShop 1.3 Beginner's Guide
PrestaShop 1.3 Beginner's Guide

Joomla! E-Commerce with VirtueMart
Joomla! E-Commerce with VirtueMart


No votes yet

Post new comment

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
p
p
7
g
p
u
Enter the code without spaces and pay attention to upper/lower case.
Code Download and Errata
Packt Anytime, Anywhere
Register Books
Print Upgrades
eBook Downloads
Video Support
Contact Us
Awards Voting Nominations Previous Winners
Judges Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software
Resources
Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software