Skip to content

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

64 Comments »

    • 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.

  1. 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.

  2. 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.

  3. 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…

    • 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.

  4. 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?

  5. 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 :)

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

  7. 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.

  8. 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.

    • 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) {
      • 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.

        -(

  9. 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.

  10. 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

  11. 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.

  12. 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

  13. 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).

  14. 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

    • 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.

  15. 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!

    • 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.

  16. 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?

    • 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.

  17. 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?

  18. 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?

  19. 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

  20. 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

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

  21. 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

  22. 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?

    • 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.

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=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

I seem to find myself working with Youtubes thumbnail images quite a lot (for instance on Miniclips videos section) – and I am always having to go searching for the parameters to use to generate those thumbnail images. So I […]