Most Commented Posts The Right Way in WordPress

Just a very quick tip but nonetheless an important one. Many of you will be using any number of plugins or the database query 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?