Latest Article

Tracking WordPress Data in Google Analytics

Custom Dimensions, Events, and Goals

I recently found myself tasked with a project where I had to pass data from WordPress into Google Analytics. Like all Google APIs, the official documentation for Analytics is incredibly vague. However, once I pieced together bits of help from all over the Internet, it turned out to be pretty easy! I’m going to save you a ton of Googling by putting it all together right here.

All of the code used in this tutorial is downloadable here and at the end of this article.

Google Analytics Dashboard

Setting Up the Base Analytics Code

Since we need to get our data with PHP and the Google Analytics code is in JavaScript, we are going to use the awesome wp_localize_script function in WordPress. It allows us to easily pass PHP variables into a JavaScript file instead of writing a messy jumble of PHP and JavaScript in our template file.

Create a new file called ga.js in your theme directory and add the stock Google Analytics code:

(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');

ga('create', 'UA-XXXXXXX-Y', 'auto');

Make sure to replace UA-XXXXXXX-Y with your property’s ID. Also, we’re going to leave off the final line of code (ga('send', 'pageview');) because we’ll be doing special stuff with that later.

Next, in your theme’s functions.php file, create an empty function that will contain all of our PHP code. We will attach it to the wp_enqueue_scripts hook so that it runs at the right time during page load.

function ga_script_enqueuer() {
    // All of the PHP code in this tutorial
    // must go inside of this function!
}
add_action('wp_enqueue_scripts', 'ga_script_enqueuer');

Inside of this function, the first thing we need to do is enqueue the new ga.js JavaScript file:

wp_enqueue_script('ga', get_template_directory_uri() . 'ga.js');

With the script enqueued, we can then use wp_localize_script to pass PHP variables into it.

Let’s take a quick look at how this function works. Take the following example:

$custom_data = array(
    'hello' => 'Hello ',
    'world' => 'world!'
);

if (isset($custom_data)) {
    wp_localize_script('ga', 'CustomData', $custom_data);
}

This bit of PHP in functions.php first sets up the custom data as an array in the $custom_data variable on lines 1-4. Line 7 passes that variable into the ga.js file. You’ll notice the first argument for wp_localize_script is 'ga' which matches the handle we used to enqueue our JavaScript file in wp_enqueue_script. This is very important as it tells the function which enqueued script you are passing this data into. The second argument, 'CustomData', is just a name for the JavaScript object that will contain our custom data. This can be anything you want.

Now we can access that data inside of ga.js just like you would any JavaScript object:

var hello = CustomData.hello,
    world = CustomData.world;

console.log(hello + world);

For the rest of this tutorial, we’ll be using this technique to pass the WordPress data into the ga.js file.

Hot Tip! Install the Google Analytics Debugger for Chrome. This will log everything your analytics code is tracking to the browser console.

Custom Dimensions

Google defines a dimension as data that describes a characteristic of your users. An example of this in WordPress would be a user’s username. Let’s create a custom dimension that will collect a logged-in user’s username.

First, you need to setup the dimension in the Google Analytics dashboard. Log in and open up the property (website) you want to add the dimension to. Go to the Admin page and click on Custom Dimensions. Create a new dimension and name it “Username”. The Scope depends on how often this data potentially could change. Will the value of your dimension change between page hits or between sessions? In our case, we are tracking the username which won’t be changing anytime soon, so let’s choose User as our scope.

Custom Dimension in GA

Save your new custom dimension and grab the JavaScript code snippet. We will be using that later.

ga('set', 'dimension1', dimensionValue);

Next, we need to get our logged-in user data in functions.php:

if (is_user_logged_in()) {
    $user = wp_get_current_user();
    $ga_user_data = array(
        'username' => $user->user_login
    );
}

if (isset($ga_user_data)) {
    wp_localize_script('ga', 'User', $ga_user_data);
}

(Remember, this should go in our ga_script_enqueuer function we created earlier.)

Finally, in our ga.js file, we can use that data to set our custom dimension’s value and then send the pageview to Google Analytics:

var username = User.username;

if (username) {
    ga('set', 'dimension1', username);
}

ga('send', 'pageview');

Custom Events

An event in Google Analytics is any type of interaction your users make with your website. The most common example is tracking how many times a link on your site is clicked. There’s nothing special that you need to do in WordPress to track link clicks. It’s handled just like any website.

We’re going to use the following button as an example:

<button id="important_btn">Click me</button>

All we need to go is add the following JavaScript to ga.js:

document.addEventListener('DOMContentLoaded', function(event) {

    var importantBtn = document.getElementById('important_btn');

    importantBtn.addEventListener('click', function() {
        ga('send', 'event', 'button', 'click', 'Important Button');
    });

});

If you’d like to learn more about how we’re using the ga() function here, check out Google’s documentation for event tracking. You can categorize events and set multiple events on a single element. There’s more options than I’m going to get into here.

BESbswyBESbswyBESbswyBESbswyBESbswyBESbswyBESbswyBESbswyBESbswyBESbswyBESbswyBESbswyBESbswyBESbswyBESbswyBESbswyBESbswyBESbswyBESbswyBESbswyBESbswyBESbswyBESbswyBESbswy

Custom Goals

Goals are Google Analytics’ way of tracking user conversions on your site. Some goals you may have on a WordPress site are:

  • A user registers on your site
  • A contact form is submitted
  • A comment is submitted on your blog

Let’s use that last one as our example and create a custom goal that will record blog post comments.

The first thing we need to figure out is how to evaluate when a user successfully submits a comment. We can’t just track clicks on the “Submit” button because the comment form may not have validated, forcing the user to submit (and click) again. WordPress has a hook called comment_post_redirect which occurs after a user has successfully submitted a comment, so we’re going to use that. Next, we need to decide how we want Google Analytics to know that the goal was completed. One of the easiest ways is to add a parameter to the URL that will fire a custom event. Our goal will be recorded when that event is fired. We’re going to use submitted=1 as our parameter.

Add the following to functions.php:

function redirect_after_comment($location, $comment) {
    $location = preg_replace("/#comment-([\d]+)/", "?submitted=1#comments", $location);
    return $location;
}
add_filter('comment_post_redirect', 'redirect_after_comment');

The comment_post_redirect hook is in charge of redirecting the user back to the post after comment submission. Our redirect_after_comment() function takes this URL and adds our custom parameter to it. With this function in place, try submitting a comment on your blog. You should be redirected back to the post and the URL in your browser should look something like: http://example.com/hello-world/?submitted=1#comments.

(The #comments part of the URL is just an anchor link to bring the user back down to the comments section on your post.)

Next, we have to add a new custom event to our ga.js code. This event is what Google Analytics will use to determine if our goal has successfully been completed. JavaScript doesn’t have a built-in function to get URL parameters, so we’re going to have to add one. Put this at the top of your ga.js file:

function $_GET(q,s) {
    s = s ? s : window.location.search;
    var re = new RegExp('&'+q+'(?:=([^&]*))?(?=&|$)','i');
    return (s=s.replace(/^\?/,'&').match(re)) ? (typeof s[1] == 'undefined' ? '' : decodeURIComponent(s[1])) : undefined;
}

If you’re familiar with the $_GET variable in PHP, this function will let you do the same thing in JavaScript. Using this function, we will check for the submitted=1 parameter and if it’s there, we fire our custom event. Add the following to your ga.js file:

var submitted = $_GET('submitted');

if (submitted === '1') {
    ga('send', 'event', 'comment', 'submission', 'Comment Submission');
}

Now we have to setup Google Analytics to record these events as successful goal conversions. In your analytics dashboard, go to Admin → View → Goals and then click on New Goal.

In the Goal Setup section, choose Custom as the template and then click Next Step.

Custom Google Analytics Goal - Step 1

In the Goal Description section, name your goal “Submitted Blog Comment”. For the Type, choose Event so that we can track this goal via the custom event we created. Click Next Step.

ga-custom-goal2

Finally, in the Goal Details section, set the following:

  • Category equals to → comment
  • Action equals to → submission
  • Label equals to → Comment Submission
ga-custom-goal3

You’ll notice that these values are identical to the event arguments we used in our custom event. This is important! Save the new goal and you’re all done.

Submit a few comments on your blog as a test. If you have the Google Analytics Debugger installed in Chrome, you’ll see your event fire after you submit your comment and the page reloads. It will take a couple of hours before you’ll start seeing your goal show up in your analytics dashboard.

That covers the basics of using Google Analytics custom dimensions, events, and goals in WordPress. You can do some intense user tracking in WordPress if you have a handle on how to get data out of WordPress and how to marry PHP data with Google Analytics’ JavaScript. Hopefully this article helped you out and you can build even cooler things on top of it. Let me know what you come up with in the comments!

Download all of the code used in this article →

Adam Walter

Adam Walter is a front-end developer, lover of WordPress, and Director of Development at Vital in Portsmouth, NH. Read more about me →