WordPress hack: Get popular posts by comments count

May 11, 2010 at 3:35 pm

In blogging, it is useful to be able to display your most popular posts. There’s WordPress plugins to do that, but you don’t need it: This code will display your most popular posts, accordoing to the comments count, without requiring you to use a plugin.

Simply paste the following code where you want to display your most popular posts to be displayed:

$pop = $wpdb->get_results("SELECT id, post_title, comment_count FROM {$wpdb->prefix}posts WHERE post_type='post' ORDER BY comment_count DESC LIMIT 10");

<ul>
foreach($pop as $post) : ?>
<li> <?php echo $post->post_title; ?> </li>
<?php endforeach; ?>
</ul>

Thanks to Neil Skoglund for this nice piece of code!

Tags: