Jetpack is a plugin offered by WordPress.com, and it contains a variety of services, each of which can be activated or deactivated within Jetpack, depending on what you want to use.
One of the features is web site statistics. You create a WordPress.com account and then associate it with your Jetpack plugin. Then Jetpack keeps track of statistics for your site on WordPress.com. You can log in there and view what’s going on, or right in your own site you can view some charts and graphs.
On the sites we build at work we have a Social bar, with the usual colleciton of social traffic indicators. You can see it here: http://www.salinehornets.com/. One of the things we wanted there was an indication of how many times the specific articles had been viewed.
Through a long voyage of discovery about why various plugins that claimed to do this were failing, AND some wonderful support from Andy at Automattic, I figured out a good way.
Jetpack provides a function called
stats_get_csv that queries WordPress.com, and here’s how I’m using it:
$args = array(
$result = stats_get_csv('postviews', $args);
The -1 indicates infinity, so I’m asking for all days, unlimited, and I’m giving it the post_id I’m looking for.
Then in the function call I’m telling it I want postviews. That gets me an array that looks like this:
 => Array
[views] => 2
So I then do something like this:
$views = $result['views'];
This is all in a function, hence the return.
stats_get_csv function caches for 300 seconds, so you won’t necessarily see instant changes as you reload your page. You probably also should be caching on your own end, so that you’re not even hitting it that often. We’re doing whole page caching, so that my archive page doesn’t make 10 calls at once on that page.
There’s precious little documentation about this process, which is one of the reasons I did this post.
The plugin we tried using before this wasn’t passing the post_id, it was trying to get stats for ALL posts, and then loop through them and grab the one we wanted. The problem is that the function doesn’t return ALL posts, it returns the top 30 or so. It’s much more efficient to simply ask for the one you want.