How to Show The Most Commented Posts In The Sidebar

There are many ways to gauge the popularity of a post and the easiest way of them all is to check the posts with the most number of comments.

Here’s now you can display the popular posts (most commented) in the sidebar.

Open your functions.php file and copy the following code:

add_filter('widget_text', 'do_shortcode');
add_shortcode('show_popular_posts', 'wpdailybits_popular_posts');
function wpdailybits_popular_posts($atts)
{   global $wpdb;  	
    extract(shortcode_atts(array(
		'num'=>5
	), $atts));
    $num = $atts['num'];
    $posts = $wpdb->get_results("SELECT comment_count, ID, post_title FROM $wpdb->posts ORDER BY comment_count DESC LIMIT 0 ,  $num");  
    $popularposts = '';    
    if($posts)        
    {   $popularposts .= '<ul class="popularpostlist">';
	    foreach ($posts as $post) 
        {   $id = $post->ID;  
            $title = $post->post_title;  
            $count = $post->comment_count;  
            if ($count != 0) {  
              $popularposts .= '<li><a href="' . get_permalink($id) . '" title="' . $title . '">' . $title . ' ('.$count.' comments)</a></li>';  
            }  
        }    	
        $popularposts .= '</ul>'; 
    }	
    wp_reset_query();
    return $popularposts;
}

Then in the widget area of WordPress, drag a new text widget to the sidebar and enter [show_popular_posts num="5"] where num is the number of posts to show.

Showing most commented posts from the last 3 months

To show the most commented posts only from the last 3 months, use the following code instead:

add_filter('widget_text', 'do_shortcode');
add_shortcode('show_popular_posts', 'wpdailybits_popular_posts');
function wpdailybits_popular_posts($atts)
{   global $wpdb;  	
    extract(shortcode_atts(array(
		'num'=>5
	), $atts));
    $num = $atts['num'];
    $last3months = date('Y-m-d', mktime(0,0,0,(date("m")-3),date("d"),date("Y"))); 
    $posts = $wpdb->get_results("SELECT comment_count, ID, post_title FROM $wpdb->posts WHERE post_date > '$last3months' ORDER BY comment_count DESC LIMIT 0 ,  $num");  
    $discussion = '';    
    if($posts)        
    {   $discussion .= '<ul class="popularpostlist">';
	    foreach ($posts as $post) 
        {   $id = $post->ID;  
            $title = $post->post_title;  
            $count = $post->comment_count;  
            if ($count != 0) {  
              $discussion .= '<li><a href="' . get_permalink($id) . '" title="' . $title . '">' . $title . ' ('.$count.' comments)</a></li>';  
            }  
        }    	
        $discussion .= '</ul>'; 
    }	
    wp_reset_query();
    return $discussion;
}

It should show up something like this:

popular-posts

That’s it.

Comments are closed.