Blog
Next Post »

Displaying Statistics from WordPress.com Stats

I recently had a problem with the WordPress.com Stats plugin I use. On reading the documentation for an answer I saw that, on an unrelated note, it’s possible to retrieve statistics, such as post view counts, using the WordPress.com Stats API.

I never did find an answer to my problem and it since appears to have rectified itself, but I thought I’d have a go at getting view counts for my posts using the API and including them on my blog.

UPDATE 8th May 12: I’ve released a plugin which encapsulates the functionality described below. Read more about it at Display Post View Count Plugin for WordPress.com Stats or download it directly using the link below.

display-post-view-count.zip5.9 KBMay 8, 2012 06:20

There’re two ways to access statistics using the API. The first is through a URL: http://stats.wordpress.com/csv.php. The second is using the stats_get_csv() function included with the plugin.

Using the first method I can display the total views for each individual post with the following URL:

 

http://stats.wordpress.com/csv.php?api_key=xxxxxxxxxxxx&blog_uri=http://www.tech-otaku.com&table=postviews&days=-1&limit=-1&summarize

 

Of course I can’t use this method to include statistics on my blog as it merely displays statistics in a browser. To do that I need to use the stats_get_csv() function.

Before continuing, it’s worth pointing out that the view counts returned by using the API don’t always match those shown when accessing Site Stats from the WordPress admin panel.

 

1.

Retrieving Your Blog’s Statistics

The first thing I want to do is to retrieve statistics using the stats_get_csv() function.

The stats_get_csv() function is included in the WordPress.com Stats plugin and can be found in the wp-content/plugins/stats/stats.php file. It takes two arguments. The first is the name of the table to access. The second is a string containing the necessary parameters used to query the table:

stats_get_csv('postviews', '&days=-1&limit=-1&summarize')

 

This will return an array containing data for each individual post:

Array (
	[0] => Array (
		[post_id] => 335
		[post_title] => WebTreats inFocus WordPress Theme: Customising the Display of Post Excerpts
		[post_permalink] => http://www.tech-otaku.com/blogging/webtreats-infocus-wordpress-theme-customising-display-post-excerpts/
		[views] => 3639
	)
	[1] => Array (
		[post_id] => 250
		[post_title] => Vertical, Horizontal & Diagonal Spry Sliding Panels
		[post_permalink] => http://www.tech-otaku.com/web-development/vertical-horizontal-diagonal-spry-sliding-panels/
		[views] => 2156
	)
)

 

To allow access to this data I placed the following code block in my theme’s header.php file just after the opening <body> tag:

<?php
	$post_stats = null;
	if ( function_exists('stats_get_csv') ) {
		global $post_stats;
		$post_stats = stats_get_csv('postviews', '&days=-1&limit=-1&summarize');
	}
?>

The variable $post_stats holds the array containing my posts’s statistics. I’ll be using this variable later to allow access to each of my individual post’s view count.

Note that the stats_get_csv() function has its own built-in timer which prevents it from retrieving data if called repeatedly within a given period. This timer is set to 300 milliseconds affectively caching the data for 5 minutes.

 

2.

Displaying Individual Post View Counts

I want to be able to display a post’s view count, along with other meta data, below its title, like so:

 

Here’s the function that gets an individual post’s view count. I placed this function in a separate function library. If you don’t currently use a function library you can read about setting one up here.

function userfunc_get_post_views($postID, $display_to_all = false) {
	if ( $display_to_all || is_user_logged_in() ) {
		global $post_stats;
		foreach ( $post_stats as $p ) {
			if ( $p['post_id'] == $postID ) { ?>
				<span class='stats-post-views'>
					<?php echo number_format_i18n( $p['views']) . ' views'; ?>
				</span>
		<?php }
		}
	}
}

This function takes two arguments. The first, $postID, is the ID of the post whose view count I want to retrieve. The second, $display_to_all, holds a boolean value which if true allows an individual post’s view count to be seen by everyone not just users who are logged in. If omitted the value is set to false.

Note that this function uses the $post_stats variable that was previously populated with an array of post statistics. It then iterates through this array to locate the appropriate post ID and return that post’s view count.

The class stats-post-views I’ve used for the <span> tag has the following properties;

.stats-post-views {
	color: #a9a9a9;
	float: right;
}

 

To show a post’s view count like that in the image above I call userfunc_get_post_views() like so;

<?php userfunc_get_post_views(get_the_ID(), true); ?>

In this example I’ve passed true to userfunc_get_post_views() which will ensure that view counts are displayed to everyone. Here, on my blog, I’ve omitted this value so it defaults to false and only logged-in users can see the view counts.

  Was this post helpful?  

1 Star2 Stars3 Stars4 Stars5 Stars 7 votes | 4.29 average

Loading ...  Loading ...
Email This Post

39 Comments


  1. Miguel
    Aug 30, 2010

    Hello

    I’m looking to display the wordpress.com stats in my single.php like a counter, displaying how many views the post have, because I need to deactivate the wp-stats plugin
    and I found your post, its seems to be unique.
    So i tried the solution here, but get no results until now.
    tks


    • Steve
      Aug 30, 2010

      Hi Miguel,

      …So i tried the solution here, but get no results until now.

      Is it working or not working?

      Regards, Steve.


  2. Miguel
    Aug 30, 2010

    Hello Steve, thanks for the answer.
    I put the functions code in theme functions.php , among with others. The rest I follow exactly (I think)
    Its not working, no output… (blank)…


    • Steve
      Aug 30, 2010

      Hi Miguel,

      Are you getting any output when using the URL approach: http://stats.wordpress.com/csv.php ?

      If you are, then is stats_get_csv() returning an empty array? You could use print_r() to see what data, if any, is being returned.

      Finally, this might be a dumb question, but have you enabled the WordPress.com Stats plugin?

      Regards, Steve.


  3. Miguel
    Aug 30, 2010

    I use hyper-cache plugin, but it doesnt cache when you are logged as admin. Tried the call in single.php and categories archives, after the number of comments in post info.
    A suggestion: transform the syntax of the call to to ‘if funtion exists” , so the blog dont broke if there something missing with the new funtion.


  4. Miguel
    Aug 30, 2010

    Hello Steve, thanks for the support.
    Yes, the http://stats.wordpress.com/csv.php ? return the output, when I specify the api and url, normal.
    I can run a similar script for top post as explained in this blog http://www.binarymoon.co.uk/2010/03/ultimate-add-popular-posts-wordpress-blog-1-line-code/ with success.
    so the stats_get_csv() seems to be working. But I dont want top post, I want the individual post count, as your tuto explain.
    Using wordpress stats plugin since 2008, when I migrate the site TO WP :-)

    Maybe we can try a “basic” version, without different files and the logged in/ out thing to see if it works?


  5. Miguel
    Aug 30, 2010

    Please dont publish since it have my API key :-D


    • Steve
      Aug 30, 2010

      Hi Miguel,

      …Please dont publish since it have my API key

      No worries I’ve deleted it, but the URL you included throws an error:

      Error: Either blog_id or blog_uri must be provided.

      Once you have the URL working I would try assigning the output of stats_get_csv() to a variable and then use print_r() to view the array so we can see if the function is actually returning any data.

      Regards, Steve.


  6. Miguel
    Aug 31, 2010

    Hello Steve
    I have successly opened it in 3 browsers:

    blog uri is consciencia dot org


    • Steve
      Aug 31, 2010

      Miguel,

      …I have successly opened it in 3 browsers:

      Ah, the string included an HTML encoded character for the & character. It works fine now.

      If you’re happy that get_stats_csv() is returning the correct data then the problem is probably with the userfunc_get_post_views() function. Does the array post_stats contain any data when the function executes? Is the function looping through the post_stats array?

      Regards, Steve.


  7. mehdi
    Dec 13, 2010

    hello im tired of searching for …can u help me? i have a simple question : i want wordpress.com stats for view today,yesterday,total views and users online in my website … can i have a code for this? please u r my last chance befor i go to use cystats or statpressCN to do this … i want to use it in my sidebar just like a counter
    thank u


  8. The One True b!X
    Jan 12, 2011

    Hrm. If I install everything as stated here, in the place on my site where the views should be displayed I instead get:

    Warning: Invalid argument supplied for foreach() in /home/breaking/public_html/furiousnads.com/wp/wp-content/themes/default-nads/functions.php on line 37


    • Steve
      Jan 16, 2011

      Warning: Invalid argument supplied for foreach() in /home/breaking/public_html/furiousnads.com/wp/wp-content/themes/default-nads/functions.php on line 37

      This is possibly due to an error in the original code I supplied.

      <?php
      	$post_stats = null;
      	if ( function_exists('stats_get_csv') ) {
      		global $post_views;
      		$post_stats = stats_get_csv('postviews', '&days=-1&limit=-1&summarize');
      	}
      ?>
      

      On line 4, global $post_views; should be changed to global $post_stats;

      Hope this fixes the issue.

      Regards, Steve.


  9. The One True b!X
    Jan 16, 2011

    Awesome. Thanks!


  10. Alvin Nyau
    Jan 23, 2011

    This method works like a charm! Truly appreciate it! =)


    • Steve
      Jan 23, 2011

      You’re welcome Alvin.


  11. Carlo
    Jan 25, 2011

    Good resource, thanks for sharing.
    I’ve a question, I try to retrieve some data to a post, maded few hours ago, but at the moment there are 0 visits, if I fetch directly from cvs.php. Instead If I login to my dashboard, I can see the visits that are no zero.

    The csv.php way retrieve data only from previous day? Is not live time right?
    Thanks for your answer. Regards.


    • Steve
      Jan 25, 2011

      Hi Carlo,

      The csv.php way retrieve data only from previous day? Is not live time right?

      I’m not sure it’s the previous day, but the views are certainly not as up-to-date as those shown in the WordPress Admin panel.

      Give it 24 hours and the views should begin to show.

      Regards, Steve.


  12. Carlo
    Jan 25, 2011

    Sorry another thing: I try to use your function for Individual Post Page, but I receive this error:

    WARNING: INVALID ARGUMENT SUPPLIED FOR FOREACH() IN /WP-CONTENT/THEMES/TEMA/FUNCTIONS/FUNCTIONS.PHP ON LINE

    foreach ( $stats_posts as $p ) {

    I don’t understand where I’m wrong. I use $stats_posts variable because this is the correct in last WordPress.com Stats. Can you put me in the right direction? Thanks again in advance, regards.


    • Steve
      Jan 25, 2011

      Hi Carlo,

      WARNING: INVALID ARGUMENT SUPPLIED FOR FOREACH() IN /WP-CONTENT/THEMES/TEMA/FUNCTIONS/FUNCTIONS.PHP ON LINE

      I don’t understand where I’m wrong. I use $stats_posts variable because this is the correct in last WordPress.com Stats.

      If you change one occurrence of $post_stats to $stats_posts then you need to change all occurrences throughout the entire code I supplied otherwise you’ll get errors.

      I would suggest leaving them all as $post_stats as this variable is independent of any others declared in the WordPress.com Stats plugin.

      Regards, Steve.


  13. Juani
    Mar 16, 2011

    Hi Steve, great info!!
    why you don’t use post_id=ID ?> inside the call?
    If you do that, you don’t retrieve a lot of data. You call only for the post you are interested. i’m incorrect?

    I don’t know what happen with a lot of call you do to the API.


    • Steve
      Mar 18, 2011

      Hi Juani,

      …why you don’t use post_id=ID ?> inside the call?…

      I set it up the way I did so I wouldn’t need to keep retrieving data, but you make an interesting point.

      Regards, Steve.


  14. rono
    Mar 17, 2011

    I have used this technique for the past few days with success (the stats are limited to logged in users). But since yesterday, I get sporadic post_id values in the $post_stats array; most of the posts come up with a blank post_id (I tried print_r($post_stats) and saw the catastrophe). As a result, most do not display the number of views.

    There has been no change in WordPress that I can remember that could cause this.
    Any idea?

    PS: if you check my website, I activated $display_to_all temporarily.


  15. rono
    Mar 17, 2011

    Dashboard update from WordPress.com: “(…) Currently access to stats is broken for some users and we are working on fixing this. Your stats are still being counted and will be visible once we restore access for your account.”

    It’s got nothing to do with the script.


  16. The One True b!X
    Mar 18, 2011

    Did this suddenly stop working for anyone else? I’m not sure how suddenly, but I only just noticed. I can access stats normally just fine, but the code for this in particular no longer displays anything. Can’t figure out why.


    • Steve
      Mar 18, 2011

      I believe there’s currently a problem with WordPress.com Stats. The stats are not showing on my site.

      Regards, Steve.


  17. The One True b!X
    Mar 19, 2011

    But it’s got to be a problem with whatever it is about stats that this plugin accesses, yes? Did WP change whatever it is that this plugin calls in order to get data? Because I can still see stats just fine through my WP admin area.


    • Steve
      Mar 19, 2011

      The One True b!X

      But it’s got to be a problem with whatever it is about stats that this plugin accesses, yes? Did WP change whatever it is that this plugin calls in order to get data?…

      The stats_get_csv(‘postviews’, ‘&days=-1&limit=-1&summarize’) now returns an array where both the post_id and post_title are blank.

      Array (
      	[0] => Array (
      		[post_id] =>
      		[post_title] =>
      		[post_permalink] => http://www.tech-otaku.com/
      		[views] => 4221
      	)
      )
      

      Of course without the post_id this method will not work.

      Interestingly, the URL returns the same data with the blank post_id and post_title.

      ,,http://www.tech-otaku.com/,4221
      ,,http://www.tech-otaku.com/,4127
      ,,http://www.tech-otaku.com/,2508
      

      It appears that the WordPress.com Stats postviews table no longer contains post_id or post_title. Why? I don’t know, but can only assume it’s something WordPress.com Stats have done.

      I’ll let you know if I find anything further.

      Regards, Steve.
       
       
       
       
      EDIT

      Just noticed that the post_permalink is now also incorrect as every one is shown as the home page URL.


  18. Pete Wood
    Mar 23, 2011

    Thank god I found this post, as this has been driving me crazy for a week. It used to display the “page count” on each page which I was retrieving using the same methods in this post. However over night it seems to have stopped working! Why have WordPress removed this useful feature!


  19. Pete Wood
    Mar 23, 2011

    Sorry I forgot to ask if anyone can recommend an alternative stats / page count plugin since wordpress seem to have removed this useful feature. Many thanks


    • Steve
      Mar 23, 2011

      Hi Pete,

      A few days ago I installed the Jetpack plugin which I think supersedes the WordPress.com Stats plugin. There was no immediate change, but within 24 hours the post_id and post_title were included in the data. I don’t know whether this was merely a coincidence.

      While no longer showing the root URL for every post the post_permalink now shows links to external sites. Weird! The Popular Posts displayed in my site’s sidebar and at the foot of each post are based the stats from WordPress.com. With the exception of post_permalink they seem to be working OK at present.

      There’s also a post about the issue here.

      Regards, Steve.


  20. ken
    Aug 23, 2011

    does it still work now?


    • Steve
      Aug 23, 2011

      Hi ken,

      Yep, it’s been working fine. Although I eventually had to ditch the Jetpack plugin in favour of the old WordPress.com Stats plugin as the former was breaking this site’s page navigation.

      Regards, Steve.


  21. Erik Rubright
    Oct 14, 2011

    I’m curious if there’s a way to get this/similar code to work with the Jetpack version of stats?


    • Steve
      Oct 14, 2011

      Hi Erik,

      It should work fine as-is with the Jetpack version as it uses the same API. I was originally using it with the WordPress.com Stats plugin and when I switched to Jetpack it continued to work without issue.

      I’ve since had to switch back to the WordPress.com Stats plugin for an unrelated issue.

      Regards, Steve.


  22. Henry
    Feb 29, 2012

    Will try this function out tomorrow with JetPack and write back with an update


  23. Henry
    Feb 29, 2012

    Hi Steve

    I have implemented but assume it will take a day or so for the stats to populate in the page?

    Henry, London UK.


  24. Henry
    Feb 29, 2012

    Apologies for the many posts. I just tested page load speed with JetPack activated as it seems to add over 2 seconds to the load time. Tested using Pingdom.com. The alternative is to use Google Analytics API but authentication slows page load. I think i’m going to opt for performance over displaying public stats at this point.

Leave a Reply

A native Brit exiled in Japan, Steve spends too much of his time struggling with the Japanese language, dreaming of Fish & Chips and writing the occasional blog post he hopes others will find helpful.

Next Post »

Calendar