Quick and Easy Popular Posts for Your WordPress Blog – in Only 1 Line of Code

Adding a list of popular posts to your website is a great way to increase user engagement on your site. It shows your readers what people are reading and interacting with the most - which in turn should encourage people to browse around your website more.

There are lots of posts across the blogosphere describing how to do this. Some look at the number of comments, and others track the page views, but they are all quite complex and cumbersome.

I even developed a system for looking at the most popular posts based upon comment count, with a date limit to keep things recent, and it worked (you can still see it in action on the homepage carousel), but wasn't perfect.

Then today I had a brain(fart)wave.

I have used the WordPress stats plugin for a while and it displays a nice little list of the most popular posts on the WordPress Dashboard... and I got to thinking - "why don't I use that list myself?"

My first stop was the plugin code - and 5 minutes later I had found a very simple couple of lines of code that would grab the most popular posts using the stats api.

5 minutes after that I had written the following code, and added it to the #footer of this very site (it's in the right hand column labelled "Currently Hot").

<?php
	if (function_exists('stats_get_csv')) {
		$top_posts = stats_get_csv ('postviews', 'days=7&limit=8');
		
		if (count($top_posts) > 0) {
			echo '<ol>';
			foreach ($top_posts as $p) {
?>
				<li><a href="<?php echo $p['post_permalink']; ?>"><?php echo $p['post_title']; ?></a></li>
<?php
			}
			echo '</ol>';
		}

	}
?>

This code works really well, the stats are accurate, and it even has built in database caching. What's not to like?

Note: The WordPress stats plugin, fully enabled, is a requirement for this to work.

Oh - and if you want the 1 line version check below. Personally I prefer the slightly longer version above.

<?php foreach ($top_posts = stats_get_csv ('postviews', 'days=7&limit=8') as $p) { ?><a href="<?php echo $p['post_permalink']; ?>"><?php echo $p['post_title']; ?></a><?php } ?>

Share This...

About The Author

Ben Gillbanks

Web Designer, Video Gamer, Blogger, and part time Entrepreneur. Read More

62 thoughts on “Quick and Easy Popular Posts for Your WordPress Blog – in Only 1 Line of Code

  • Reply ›
    Lucian Apostol

    I'm not a fan of WP stats plugin, it is worth using ?

    March 15, 2010

    • Reply ›
      Ben

      I quite like it myself. It's very simple, and I use Google Analytics as well, but as a simple way to get some quick numbers it's a cool thing to add.

      March 15, 2010

  • Reply ›
    Leland

    This is a really cool idea. I had been using the Popularity Contest plugin but this one seems so simple as it displays data already used by the WordPress.com Stats plugin.

    March 15, 2010

  • Reply ›
    joen

    I like this a lot. Excellent idea.

    Now if only there was a way to have this be part of the official plugin... i don't like themes having to rely on a plugin.

    Excellent stuff as always Ben.

    March 16, 2010

    • Reply ›
      Ben

      Are you hinting that I make a plugin? :) Could be a nice little extra to add in.

      March 16, 2010

      • Joen

        Yes, either that, or you pull your WordPress strings to have the author of the WordPress Stats plugin integrate this code directly :)

        March 16, 2010

      • Ben

        You know who the author is right? I guess I could ask :)

        March 16, 2010

      • Joen

        Well the author is Automattic, innit?

        I mean you're more of a WordPress rock star than I am, if anyone can get through to them with this brilliant suggestion, it would be you!

        March 16, 2010

      • Ben

        I've sent them an email asking. Let's see what they say :)

        March 16, 2010

  • Reply ›
    ElShaddai Edwards

    Great tip! Is there an argument for stats_get_csv to exclude specific page/post IDs from the results? I tried "exclude=", but that didn't seem to work...

    March 16, 2010

    • Reply ›
      Ben

      There's no documentation on the function but my guess is no. The query gets passed to a wordpress.com site so it's not as flexible as the query_posts command (for example).

      If you print_r the value of p in the foreach loop then you can see the post/ page ids so there's no reason you couldn't add in an if statement or two to exclude the posts you want to hide.

      March 16, 2010

    • Reply ›
      jjsulzbach

      I put up a post in the WordPress "Hacks" forum in which I gave the code for a wrapper function I wrote to exclude the homepage from results returned to calling code requesting a Most Popular Posts list at:

      http://wordpress.org/...epage-from-stats_get_csv-results

      And my thanks to Ben Millbanks here for his own calling code, which formed the basis for constructing a solution. Thanks Ben!

      October 3, 2010

  • Reply ›
    Jason Cosper

    I kluged together a widget for the folks who want to put this in their sidebar:

    http://github.com/boogah/Trendy

    Thanks for the code!

    March 17, 2010

  • Reply ›
    George

    Hey Ben, not strictly related with this post....but just downloaded ur Regulus theme for my WP blog. Thanks, really sweet design. Would like a bit more functionality however, such as the addition of a navigation menu for the pages...or a pull down menu when the page titles are hovered over - if you know what I mean. As I am new to this WP gig...what would your suggestions be in order for me to do that? Can you help?

    March 26, 2010

  • Reply ›
    Pepijn de Vos

    Hey,

    Good stuff!

    It seems I'm not the only one who figured this out.
    My post: http://pepijndevos.nl/...ess-com-stats-top-posts-widget/
    Another post I found: http://darylteo.com/...14/do-you-use-wordpresscom-stats/ << he was apparently first.

    The plugin FAQ is linking here by the way...

    April 1, 2010

  • Reply ›
    eMAGaZine

    Hi.. Ben.. Awesome stuff!
    I just want to know, how to display my TOTAL stats just like blog at wordpress.com in sidebar? In another case, for example to show off my Akismet stats, I just put in my sidebar template. So, If I want to show off my stats, what should i do?

    Thanks!
    *sorry for my bad english.. I'm from Indonesia :)

    April 2, 2010

  • Reply ›
    majin22 @ SlackerMommy.com

    I have used your code to create my own "most popular" page - http://slackermommy.com/...ending-wordpress-stats-plugin

    Thanks again for the code

    April 13, 2010

  • Reply ›
    Jose

    Nice work.
    I wonder if it is possible to filter the shown posts by categories for instance.
    Thanks for the help.

    April 16, 2010

  • Reply ›
    Dan

    Hey Ben, do you know if it's possible to replace the post title with the new post thumbnail feature? I've been searching for days to find a way to sort the post and display them as thumbnails for days, but nothing seems to be working. Thanks for any help.

    April 22, 2010

  • Reply ›
    phil

    Hi there, firstly thanks fort this, very useful. Do you have any idea how to remove the home page from the outputted stats though, for me (and most id assume) the home page is going to always be the most popular, and it would be good to not have this added in the mix.

    Thanks in advance.

    May 1, 2010

    • Reply ›
      Ben

      I actually added this myself after I wrote the article :)

      It's quite easy to do. Just add a conditional, inside the foreach loop that checks if the post_id is > than 0. Something like:

      if ($p['post_id'] > 0) {

      May 8, 2010

      • phil

        Hi Ben, thanks for the response. I can not for life of me get this working, I just get the blankscreen or no change. I will continue to bang my head against the wall on this until I get it fixed (I hope). Problem lies obviously with my misunderstanding of conditional tags and how to properly implement them, im a total trial and error donk with this stuff, but this one isnt coming as easy as the rest.

        If you could see your way as to actually spell it out for me, I would be evry grateful. Its certianly not working above the below echo, and I can find a way to get it working in the above loop, I figured I need to go if then else to let it move on to the next if statment but nope.

        -(

        May 9, 2010

  • Reply ›
    Robert

    Thanks for coming up with this & sharing it. I was looking at Popularity contest for most pop, but think I will use this since I have stats already installed. I was able to filter out the home page, thanks for that as well (for Phil, the conditional goes after the foreach statement but before the opening curly bracket).

    Two things I noticed though, and was puzzled by: I changed the 'limit' statement at the beginning to 11 from 8 to get a net of top ten items, but it did not come through for some reason (after taking out home page, I got a net of seven). Need to do something different? Also I was wondering how to filter out pages, and show only posts.

    Above all, thanks again for sharing this snippet, its a huge help for me.

    June 26, 2010

  • Reply ›
    Alan B.

    Hi Ben,

    Any chance you can provide updated code with the conditional inserted to remove the homepage for us folks who are not PHP programmers?

    Thanks,
    Alan

    July 2, 2010

  • Reply ›
    Challe

    Great! But please share the code to remove the homepage in the code, this make it much better. Otherwise it looks unprofessional and maybe not worth the extra loading time for the WordPress Stats plugin in admin cpanel.

    July 9, 2010

  • Reply ›
    Levent

    Creative idea Ben.. And thanks for your effort. I sure will use this idea on my blog

    July 16, 2010

  • Reply ›
    Miguel

    Its possible to make an example to show the total post view placing a call in single.php? i.e Use the stats service like a hit counter for each individual post, like wp-stats plugin

    August 30, 2010

  • Reply ›
    stone crusher

    Hi Ben, thanks for the response. I can not for life of me get this working, I just get the blankscreen or no change. I will continue to bang my head against the wall on this until I get it fixed (I hope).

    September 20, 2010

  • Reply ›
    Simone

    Hi Ben,

    Is there a chance to filter posts by category? It would be extremely nice to be able to do so to recreate top posts for each individual category as it would give the ability to create website charts for viewers.

    Thanks in advance,
    Simone

    October 28, 2010

    • Reply ›
      Ben

      Not that I'm aware of I'm afraid. This plugin is used purely for tracking the top performing posts and doesn't take categories into account.

      October 31, 2010

  • Reply ›
    Simos

    hi! nice work! but is there a way to display the most viewed posts published on a certain date?

    ex. most viewed articles edited the last 24hours or the last week.

    All most viewed widgets display all the articles, even old and good SEO ones so the list is not interesting for daily viewers.

    Thank in advacne!

    December 3, 2010

    • Reply ›
      Ben

      I am afraid there isn't a way to do this with the WordPress.com stats widget. That doesn't take into account article age.

      December 4, 2010

  • Reply ›
    Konstantinos

    Hi Ben,
    is there any way to put in every post the total number of its views?
    for example: http://lesterchan.net/...o/programming/php/#wp-postviews

    Thanks anyway and congrats!
    :-)

    December 13, 2010

    • Reply ›
      Ben

      Hi there. I suspect there is a way to do this but I have not done it myself. What I would do is add print_r($p) inside the foreach loop and see what values it prints out.

      December 15, 2010

  • Reply ›
    John

    I put in the code and it's returning pages as well as posts. Is there a way to limit it to just posts?

    March 16, 2011

  • Reply ›
    John

    Not sure if my last comment went through.

    Basically, I added in the code but it's showing my pages along with my posts. I'd like to only show posts. Also, is there a way to add an array of custom post types to this?

    March 16, 2011

    • Reply ›
      Ben

      I am afraid there isn't a way to limit it. It simply returns a list of urls. You wold ned to loop through the urls and compare with a list of page urls to be able to hide the pages from the list.

      March 17, 2011

  • Reply ›
    Abhijeet Mukherjee

    Hi, I have been using this code for a long time to display currently popular posts on the sidebar of guidingtech.com and guidingtech.com/mobiles/. But it suddenly stopped working a few days back and didn't show anything. It was probably because of the WP Stats issue. Now, the wordpress stats plugin is working fine but this code. You can check the URLs. You'll find that it is showing weird URLs under the currently popular section in the sidebar. How to fix that?

    March 24, 2011

  • Reply ›
    Hody

    Would like to show the total users or the daily user number in a widget based on the number of wordpress.com stats. Until now I have failed to find a widget that can do so, maybe you can help me out here?

    March 24, 2011

  • Reply ›
    Hody

    Yes, I tried to put the code in a widget, but I guess it does not work there anyhow.
    I would like to display the number of overall visitors at the buttom of my page. Before when my blog was hosted at wordpress.com that supplied an easy widget to to that, but now on my selfhosted blog I fail to somehow display the overall number that can be found under Jetpack / Stats

    April 4, 2011

  • Reply ›
    Benoît Melançon

    Ben,

    Thanks for the code. It works great with my blog (oreilletendue.com, at the bottom of the page).

    There's one small glitch though.

    My blog is in French, so it uses accented uppercase characters: some words start with E (or A), others with É (or À).

    In the list of my most popular posts, if the first letter of the post title is an accented uppercase character, this first letter disappears : Éloge becomes loge; À propos becomes propos.

    You have an idea why it is so?

    Many thanks again.

    Benoît

    April 16, 2011

  • Reply ›
    Harry

    This doesn't work with Jetpack, and I cannot find the WordPress Stats plugin anymore!

    April 20, 2011

    • Reply ›
      Hody

      Hello Harry, had that mentioned above already. I am in desperate search for the functionality/Plugin as well, hope there will be something soon...

      April 23, 2011

  • Reply ›
    Fajar

    hi ben, i was wondering if we can display the view count as well. Can we do that?

    Thanks in advance. your code is great =D

    July 28, 2011

  • Reply ›
    Cx Rana

    nice tricks for new wp developer...

    October 25, 2012

  • Reply ›
    Chota Bheem

    Basically, I added in the code but it's showing my pages along with my posts. I'd like to only show posts. Also, is there a way to add an array of custom post types to this?

    January 18, 2013

  • Reply ›
    pantuts

    O yeah! As wp plugin release maybe? :)

    February 25, 2013

    • Reply ›
      Ben

      There's not much that can be done in terms of turning this into a plugin I am afraid. I think that you would be better off using the Jetpack plugin which I believe has this integrated.

      March 4, 2013

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title="" rel=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Websites linking here

  1. Favicon for http://www.google.com/s2/favicons?domain=www.themelab.com Useful Alternatives to WordPress Monthly Archive Links | Theme Lab
  2. Favicon for http://www.google.com/s2/favicons?domain=www.binarymoon.co.uk WordPress query_posts Tips

My Projects

TimThumb - Image Resize Script TimThumb

Image Resize Thumbnail Script

WPVote - WordPress Social Voting WPVote.com

WordPress Social Voting Site

About me

About BenMy name is Ben Gillbanks. I'm a lover of Video Games, WordPress, Web Development and everything in between.

I have been working on the internet since 1998, and working with computers even longer. I am a hardcore Nintendo fanboy and have owned most of their consoles at one stage or another.

Read more about me on my about page.

Binary Moon

WordPress and Web Development › home of Ben Gillbanks