Sort Posts by Comment Count in Wordpress

Published: January 20th, 2009 by: Andrew

I use this technique to show the most popular posts on our homepage, and although this isn't a core feature in Wordpress, it's not all that hard to do. All it takes is a little PHP and a single edit to one of your Wordpress template files.


I decided not to use a plugin because I find it easier to just edit the templates directly. Here is the code:

<?php
$results = $wpdb->get_results("SELECT ID, comment_count FROM wp_posts WHERE post_type = 'post' && post_status = 'publish' ORDER BY comment_count DESC LIMIT 5");
foreach ($results as $r):
	query_posts(array('p' => $r->ID));
	while (have_posts()):
		the_post();
?>
<!-- regular wordpress loop code goes here -->
<?php endwhile; endforeach; ?>

This code manually calls a SQL query because there is no template tag that supports this method of sorting as of Wordpress 2.7. We are only querying for the post IDs because we will use that ID to call up the Wordpress loop which will allow us to use the normal template tags inside the manual Wordpress loop.

Related posts:

4 Responses to “Sort Posts by Comment Count in Wordpress”

Leave a Reply





Wordpress doesn't like it when you post PHP code. Go save your code at pastebin, and post the link here.

About the Author

Andrew has been coding PHP applications for over 5 years, and has plenty of experience with PHP, MySQL, and Apache. He prefers Ubuntu Linux on his desktop and has plenty of experience at managing CentOS web servers. He is the owner of Wells IT Solutions LLC, and develops PHP applications full time for anyone that needs it as well as does desktop computer support locally in the local area. He spends most of his free time exploring new programming concepts and posting on The Webmaster Forums.