How to Exclude WordPress Preview Pages from Piwik Statistics

Update (March 11, 2011): There's a new version of the code.

Like many people who maintain a blog, I look at my site statistics. I'm not looking for SEO reasons, though. I'm just curious whether or not anyone actually reads anything.

My site statistics page includes a list of what pages on my site are accessed. A problem is that this page is hard to read and not very customizable. My other problem is that this utility collects data for all of the web traffic that goes through this site, including my subversion repositories (a software developer utility) and blog editing interface. I wanted something a bit nicer that would only look at my blog's pages. I grepped around the web and eventually chose Piwik.

Piwik gives me a small bit of code that I put in the web page's content. This code will make Piwik collect data about that page. It recommends the code be put in the footer of the page template. The footer is automatically added to the end of every post, so I only have to add the code once. A quick copy-paste later and my blog statistics were leaps and bounds better than they were, recording data only on pages that I cared about. If you have a website, I recommend taking a look at Piwik.

War On Pants is run using Wordpress. Wordpress is an easy-to-use blogging utility. Rather than creating my entire web site from scratch, I installed Wordpress because it's fast, easy, secure, and powerful. I can still do everything that I want to do with my website while still being able to spend more time writing content rather than programming. I write software at work. I want to relax and just write what's on my mind when I get home.

When writing a blog post, Wordpress allows you to preview the post. When it does this, the URL (web site location) is the same as the post URL when it's published with one exception. The URL has "&preview=true" appended to it. I only realized that I had a problem after I wrote about Huckleberry Finn Censorship. My previews were being logged as page views.

Piwik Preview Error
This may be the most meta picture on War On Pants to date.

The code I added to the footer of my blog pages didn't know that the preview shouldn't be included. I needed a way to remove the code only on preview pages.

Luckily, Wordpress is PHP based. Knowing everything written above, two lines of code solved my problem.

<?php if (! preg_match('/.*preview=true.*/', $_SERVER['QUERY_STRING'])): ?>

    Piwik-pasted code goes here.

<?php endif; ?>

preg_match is the PHP function that tests regular expressions. $_SERVER['QUERY_STRING'] is a built-in PHP variable that is equal to everything after the question mark in the URL e.g. for this page it would be "p=247". So, the code says that if the $_SERVER['QUERY_STRING'] does NOT include the phrase "preview=true", add the Piwik-pasted code to the page.