Getting feedback from your visitors is critical to understanding how your site is going, what is working and what isn’t. Web analytics is a great way to get such feedback, simply by observing how your visitors behave, how they get to your site and where do they visit. To get the best web-analytics you should use Piwik.

The first step in integrating Piwik with WordPress would be to install and configure the WP-Piwik plugin (the best plugin out there for adding your piwik tracking code into your wordpress website).

The sections below are ordered by ease of configuration and least of knowledge required (easy to less easy…), and will give you important tips on how to utilize Piwik even further.

Note: In this post I assume you have a working installation if Piwik with admin privileges and have installed and configured WP-Piwik.

Tracking Subscribed ReadersTop

Using goals is a very convenient way for monitoring important actions on your website. You can see how a visitor behaved and from what page he decided took a certain action.

When a user subscribes for updated on your website using the Jetpack subscription widget, he is redirected to the following URL http://example.com/?subscribe=success#….
What interests us is the subscribe=success, this is the tracking point we will use:

  1. In your Piwik’s dashboard, choose Goals->Goals Overview->Create a new Goal.
  2. Insert the goal’s name
  3. Select the trigger when visitors and choose Visit a given URL
  4. Select contains and input subscribe=success

Track Subscribed Users Goal

Track Subscribed Users Goal


Now, when a user subscribers, after he is redirected to the successfully registered users’ page, Piwik will track that as a single conversion.

Tracking AdvertsTop

The best way to track usage of adverts with Piwik it to use the goals feature. For this we will use a goal that updates manually, and then set the code for updating it.

  1. In your Piwik’s dashboard, choose Goals->Goals Overview->Create a new Goal.
  2. Insert the goal’s name
  3. Set the trigger to manually
  4. Select the Goals Overview again and write down your new goal’s ID, we will use it later.
  5. If the clicked adverts are worth money, you can also add a revenue value to see how much you should be earning.

Track Adverts Goal

Track Adverts Goal


Now, for the tracking part. I am assuming you are using the AdRotate plugin, but the technique is identical for every type of adverts.

Add an onclick event to the advert link’s anchor with the code below, where GOAL_ID is the ID of the goal we created before.

1
javascript:_paq.push(['trackGoal', GOAL_ID]);

Here is a complete example for a code that tracks an image advert using AdRotate:

Advert Code
1
2
3
<a href="%link%" onclick="javascript:_paq.push(['trackGoal', 2]);">
    <img src="%image%"/>
</a>

This works because Piwik’s tracking code from `WP-Piwik` already exists in the header and has been initialized. So you can use the same Javascript code in the rest of your page to track other things.

Tracking Registered UsersTop

Tracking newly registered users is especially relevant for websites with a community. For example a site running BuddyPress, forums or some other kind of community mechanism.
The idea is very simple. You create a goal on piwik, and add some code to wordpress to update that goal when a new user registers to the website (The wordpress action that occurs when a new user registers is user_register). In order to link the tracked action of the registration to the currently active visitor, we add the goal-tracking code to the website on the footer, hence allowing to link between the visitor and the registration (Important when you want to monitor how and from where users register).

  1. In your Piwik’s dashboard, choose Goals->Goals Overview->Create a new Goal.
  2. Insert the goal’s name
  3. Set the trigger to manually
  4. Select the Goals Overview again and mark your new goal’s ID, we will use it later.

    Track Registered Users Goal

    Track Registered Users Goal

  5. Add the code below to your functions.php file
  6. Change YOUR_GOAL_ID in the code (line 12) to your goal’s ID
functions.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
<?php
if (!class_exists("TrackUserRegisteration")) {
    class TrackUserRegisteration {
        var $trackRegisteredUserGoal = FALSE;
 
        function piwik_footer() {
            # If this page is returned right after a user registered,
            # track the action
            if ($this->trackRegisteredUserGoal) {
            ?>
<script type="text/javascript">
    _paq.push(['trackGoal', YOUR_GOAL_ID]);
</script>
            <?php                        
            }
        }
 
        function track_user_register($user_id) {
            # Mark the page's footer to contain the tracking code
            $this->trackRegisteredUserGoal = TRUE;
        }
    }
} //End Class TrackUserRegisteration
 
if (class_exists("TrackUserRegisteration")) {
    $dl_wpPiwikExtender = new TrackUserRegisteration();
}
 
if (isset($dl_wpPiwikExtender)) {
    # Action that runs when a new user registers
    add_action('user_register', array(&$dl_wpPiwikExtender, 'track_user_register'));
    # A filter for updating the page's footer
    add_filter('wp_footer', array(&$dl_wpPiwikExtender, 'piwik_footer'));
}

Utilizing AnnotationsTop

Annotation are a great feature Piwik added recently. It allows you to see how changes you made to your website affected visitors. A good way to use them would be to add an annotation when you changed the layout, published new content, etc.

Automatically Create Annotation for a New PostTop

In this section I will show you how to automatically add annotation whenever you publish a new post (This concept can be replicated to pages and other type of content).
To create an annotation whenever a new post is published, add the following code to your functions.php.

functions.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
<?php
/*
Random string generator is based on http://stackoverflow.com/questions/4356289/php-random-string-generator
*/
function generateRandomString($length = 10) {
    $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $randomString = '';
    for ($i = 0; $i < $length; $i++) {
        $randomString .= $characters[rand(0, strlen($characters) - 1)];
    }
    return $randomString;
}
 
/*
Create annotation when a new post is published
*/
function tell_me_on_post($post_id) {
    // The random value is used for anti-caching
    $randPeriod = $this->generateRandomString(5);
    $title = get_post($post_id)->post_title;
    // Define the annotation's content
    $note = urlencode("Published Post: $title");
    $GLOBALS['wp_piwik']->callPiwikAPI(
		'Annotations.add', // The method's name
		$randPeriod,	   // A random value, for Anti-Caching purposes
		date("Y-m-d"),     // The date of the publish
		null,
		false,
		false,
		"PHP&note=$note"   // Hacking the wp-piwik api for adding more options
		);}
 
// Action occurs when a post's status is changed to `publish`
add_action('publish_post', 'tell_me_on_post');

Code explainedTop

$GLOBALS['wp_piwik'] is defined in the WP-Piwik plugin and points to a class that has the function callPiwikAPI. See the code below for the relevant snippet of this function:

plugins/wp-piwik/wp-piwik.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
/**
 * Call Piwik's API
 */
function callPiwikAPI($strMethod, $strPeriod='', $strDate='', $intLimit='',$bolExpanded=false, $intId = false, $strFormat = 'PHP', $strPageURL = '') {
	// Create unique cache key
	$strKey = 'wp-piwik'.md5($strMethod.'_'.$strPeriod.'_'.$strDate.'_'.$intLimit);
	// Call API if data not cached
	$result = (WP_PIWIK_ACTIVATE_CACHE?get_transient($strKey):false);
	.
	.
	.
		$strURL .= '&format='.$strFormat;
	.
	.
	.
	return $result;	
}

This function receives several parameters that are passed to Piwik’s API call. It is clear the writer intended to use this function for specific API methods, so we will hack it a bit in order to be able to call any API method we want, without rewriting or duplicating the WP-Piwik plugin.
As you can see, in line 6 there is an md5 created for our request based on the input parameters. This is a good idea for requests to methods that return data you might want to cache such as yesterday’s visits, but in our case we need skip the cache. To do that I added a random string to the $strPeriod variable (line 19 in my code), which is ignored when we call API methods that don’t require it.
Next, as you can see in line 12 the $strFormat is used for sending another parameter, without any sanity check. This allows us to send additional parameters that will be sent to the Piwik server (line 30 in my code).
Lastly, I call the relevant API Annotations.add every time a post’s status is changed to Published, thus creating a new annotation.

Monitor User Type
??? custom variable???
…And at the end, I bundled it all for a Piwik plugin you can use, which extends the WP-Piwik functionality

ResourcesTop

If you have any other ideas or question, feel free to let me know, and I will update the post accordingly.
Tagged with →  

Leave a Reply