How to: Display your most popular content in your blog sidebar

March 25, 2009 at 10:50 am

Blog posts aren’t all equals: Some are better than the others. In order to make visitors stay longer on your blog, what about giving them a quick access to your most commented posts? Here’s a nice code to do it easily.

Just paste the following code on your sidebar.php file. To change the number of displayed posts, simply change the 5 on line 3.

<h2>Popular Posts</h2>
<ul>
<?php $result = $wpdb->get_results("SELECT comment_count,ID,post_title FROM $wpdb->posts ORDER BY comment_count DESC LIMIT 0 , 5"); 
foreach ($result as $post) { 
setup_postdata($post);
$postid = $post->ID; 
$title = $post->post_title; 
$commentcount = $post->comment_count; 
if ($commentcount != 0) { ?> 
<li><a href="<?php echo get_permalink($postid); ?>" title="<?php echo $title ?>">
<?php echo $title ?></a> {<?php echo $commentcount ?>}</li>
<?php } } ?>
</ul>

Thanks to ProBlogDesign for this awesome recipe!

By the way, did you checked out WpClassipress? It is a great classified site 100% built within WordPress!