Most Commented Posts The Right Way in WordPress

Most Commented Posts The Right Way in WordPress

Posted on 06. Jan, 2010 by in Coding, Update

Just a very quick tip but nonetheless an important one. Many of you will be using any number of plugins or the database query and stored in your WordPress web hosting that’s been doing the rounds recently to display your most popular posts. That code/plugin is no longer needed as WordPress’ query_posts can now display your most commented posts.

So how’s it done? Really simple; the following should do the trick (2.9 or above):

<ul>
	<?php query_posts('orderby=comment_count&posts_per_page=>5');
	if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
		<li><a href="<?php the_permalink() ?>" rel="bookmark" title="<?php the_title_attribute(); ?>"><?php the_title(); ?> (<?php comments_number('0','1','%'); ?>)</a></li>
		<?php endwhile; ?>
		<?php else : ?>
		<li>Sorry, no posts were found.</li>
	<?php endif; ?>
</ul>

In a nutshell we’re just creating an unordered list with the five most popular posts and ordering by comment count, hence we’re able to display the most commented posts first. Now go and replace all those plugins!

Update: as Sean points out, might be better off using WP Query in order to not get in the way of any other queries you’re running. Something like the following will do the trick:

<ul>
<?php $popular = new WP_Query('orderby=comment_count&posts_per_page=5'); ?>
	<?php while ($popular->have_posts()) : $popular->the_post(); ?>	

	<li><a href="<?php the_permalink() ?>" rel="bookmark" title="<?php the_title_attribute(); ?>"><?php the_title(); ?> (<?php comments_number('0','1','%'); ?>)</a></li>

<?php endwhile; ?>
</ul>

Extending things

As Ben points out, like this, it’s nothing special. My response is you can do more exciting things. Like get an image (using the custom field ‘Image’ — change that line to the new get-the-image function to automatically get your images or the like):

<?php $popular = new WP_Query('orderby=comment_count&posts_per_page=5'); ?>

	<?php while ($popular->have_posts()) : $popular->the_post(); ?>	

	<?php $justanimage = get_post_meta($post->ID, 'Image', true);
			if ($justanimage) {
			?>
	<img src="<?php echo get_post_meta($post->ID, "Image", true); ?>" alt="<?php the_title(); ?>" />

	<?php } else { ?>

	<img src="http://an-alternative-image.jpg" alt="" />

	<?php } ?>

	<h2><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>

<?php endwhile; ?>

That’s an improvement over an unordered list, no?

Follow on Twitter! Subscribe!

WPShout is hosted by the fine folks at WPWebHost.

You can get exactly the same hosting as WPShout has for $7.95/month with WPWebHost's Freedom Plan.

Plus get 30% off the Freedom Plan with the code WPSHOUT.

Visit WPWebHost

Alex's Gravatar

Alex Denning is the founder of WPShout. A WordPress developer from London, Alex is a keen musician and freelance writer and developer.

You can find Alex on Twitter.

33 Responses to “Most Commented Posts The Right Way in WordPress”

  1. Brad

    06. Jan, 2010

    Thank you for the quick tip. I love eliminating extraneous plugins with small chunks of php.

    Reply to this comment
    • Alex Denning

      07. Jan, 2010

      That’s what it’s all about :)

      Love the design of your blog, btw!

      Reply to this comment
  2. tom

    07. Jan, 2010

    currently using Atahualpa, and that theme has a widget similar to that one, with the added option of specifying an “exclude posts prior to X days ago”… how would that option be added to the code above?

    Reply to this comment
    • Alex Denning

      07. Jan, 2010

      We’re using query_posts so it’s just a case of selecting the one you want. This link will give you a number of examples and options.

      Reply to this comment
      • tom

        08. Jan, 2010

        Ah, thanks for the link – is there no end to the PHP/Wordpress options?!

        Reply to this comment
  3. Gonzo

    07. Jan, 2010

    If there are no posts, an unordered list with a paragraph inside is generated, which will brake validation of the page. I would put the if statement around the ul. Or, surround the p tag with a li in the else case.

    Reply to this comment
  4. Ben

    07. Jan, 2010

    Cool tip but I wonder if this is overkill for getting the most commented posts? I don’t need all of the post information when I am posting popular posts so maybe a custom way would be quicker on the server/ db?

    Reply to this comment
    • Alex Denning

      07. Jan, 2010

      Perhaps although take me as an example. I want to display an image, do an if/else statement on the title (shortened version) and limit which date the post can come from – this might be best :)

      Reply to this comment
  5. Sean O'Grady

    07. Jan, 2010

    Thanks! Edited it a bit to use WP Query, helping remove conflicts with other php snippets

    query(‘showposts=5&orderby=comment_count’);
    ?>
    have_posts()) : $popPosts->the_post(); ?>
    <a href="” title=”">

    Reply to this comment
  6. Ashfame

    07. Jan, 2010

    Yes cool tip! Will use it on homepage.

    Reply to this comment
  7. Kristof

    08. Jan, 2010

    Thanks for the snippet.

    Since 2.9 includes ability for Page/Post Image/Thumbnail option, would it not be more efficient to call that thumbnail instead of adding/calling a custom field? If so, how would you modify your code snippet? Thanks.

    Reply to this comment
    • Sels

      08. Jan, 2010

      Kristof, I was just working on a post about using the post thumbnail function instead. Here’s the snippet using Alex’s example:


      have_posts()) : $populer->the_post(); ?>
      <?php if ( has_post_thumbnail() )
      the_post_thumbnail(array(60,60));
      else echo '';
      ?>
      <a href="" rel="Bookmark" title="">

      Reply to this comment
  8. isa

    17. Jan, 2010

    That is the right way, if you do not want to use a plugin while you can do it with just 5 lines of code…

    Thanks for this useful information.

    Reply to this comment
  9. Jim

    04. Feb, 2010

    Thanks for the cool little trick.. Nowi can disable some pluging.. thanks again…

    Reply to this comment
  10. Devin

    21. Jul, 2010

    Awesome. Just removed 15 unneeded database queries from a client’s site.

    Reply to this comment
  11. chibi

    23. Jul, 2010

    Is there a way to display most commented posts, but exclude comments from pages being on the list?

    Thanks

    Reply to this comment
  12. pablo

    22. Aug, 2010

    how do you exclude trackbacks from here and also only show posts with more than 1 comment.

    Reply to this comment
  13. SK

    27. Sep, 2010

    Hey everyone, great discussion going on here. One question: is there a parameter to fetch the most commented OVER a time duration?

    If I am correct this grabs the most commented posts of ALL time. Let’s say I want to set it for most commented in last 24 hours, last 7 days, or last month. Is that possible?

    I noticed there is a date parameter, but that only does it for let’s say THIS WEEK or THIS MONTH. So if it’s Monday morning or the first day of the month, there won’t be much to show off.

    Is there a way to make it so it shows most popular over the “last X days”?

    Reply to this comment
    • Antes

      25. Oct, 2010

      Thanks for the post, helped me alot. Heres my whole sidebar widget with 5 most commented posts from the past 2 weeks. Works like a charm..


      function childtheme_sidebar_popular() { ?>
      <div id="sidebar_popular">
      <div class="sidebar_popular_title"><h3>Most commented now</h3></div><!-- sidebar_popular_title -->
      <div class="sidebar_popular_content">
      <?php
      function filter_where($where = '') {
      //posts in the last 14 days
      $where .= " AND post_date > '" . date('Y-m-d', strtotime('-14 days')) . "'";
      return $where;
      }
      // Register the filtering function
      add_filter('posts_where', 'filter_where');
      $popular = new WP_Query('orderby=comment_count&posts_per_page=5');
      ?>
      <?php while ($popular->have_posts()) : $popular->the_post(); ?>
      <div class="sidebar_feature"><div class="popular_number"><?php comments_number('0','1','%'); ?></div><div class="popular_c$
      <div class="clear"></div>
      <?php endwhile; ?>
      </div><!-- sidebar_popular_content -->
      </div><!-- sidebar_popular -->
      <?php }

      Reply to this comment
  14. billboc

    16. Jan, 2011

    Hello

    how to display the number of comments for each post ?

    thank you
    regards,

    Reply to this comment
    • billboc

      16. Jan, 2011

      sorry i’ve made a mistake because in fact… this code is perfect !
      shame on me

      Reply to this comment
  15. Nicholas

    25. Jan, 2011

    I was getting rather frustrated and annoyed with the existing plugins that are out there for this. None of them seem to allow you to have control of the markup or even the location of the “widget”.

    Thanks very much for this article. it has helped me greatly!

    Reply to this comment
  16. Ido Doron

    16. Oct, 2011

    Is there any way to use get_posts() function for this action?
    Because I used this function to load the three most recent posts by this code:

    [...]
    $args = array( ‘numberposts’ => 3, ‘orderby’ => ‘post_date’, ‘order’ => ‘DESC’ );
    $myposts = get_posts( $args );
    [...]

    It worded. It loaded the three most recent posts, but when I tried to change the “orderby” from ‘post_date’ to ‘comment_count’, only one post was loaded.
    Is there any solution for this issue which doesn’t mean to use other function such as wp_query() or query_posts()?

    Reply to this comment
  17. Ido Doron

    16. Oct, 2011

    Is there any way to use get_posts() function for this action?
    Because I used this function to load the three most recent posts by this code:


    [...]
    $args = array( 'numberposts' => 3, 'orderby' => 'post_date', 'order' => 'DESC' );
    $myposts = get_posts( $args );
    [...]

    It worded. It loaded the three most recent posts, but when I tried to change the “orderby” from ‘post_date’ to ‘comment_count’, only one post was loaded.
    Is there any solution for this issue which doesn’t mean to use other function such as wp_query() or query_posts()?

    Reply to this comment

Trackbacks/Pingbacks

  1. [...] to Alex Denning for this nice trick! If you enjoyed this article, please consider sharing it! tweetmeme_style = [...]

  2. [...] Denning over at WPSHOUT posted a nice tip for displaying popular posts without the need for a plugin. You can now order [...]

  3. [...] Badly made graphic number one is actually quite heavily cropped so you don’t see the ‘Popular Posts’ section of the sidebar. For this, we followed my own advice to get most commented posts the right way: [...]

  4. [...] 2.9 or higher, you don’t really need a plugin.  So if you like to limit the use of plugins, check out this article for more [...]

Leave a Reply

Please use your real name when commenting. Wrap code in <code> tags and make sure HTML is encoded. You can use regular HTML like <a href="... etc.

Get yours questions answered quicker

If you're using this post for paid work and have a question of any complexity then please ask at WPQuestions where you'll get a prompt response.