WordPress Wednesdays: Add the most commented posts to the sidebar

Geek Factor: 3

Here is a quick way to display the most commented posts within a timeframe, so you can encourage people to join active discussions without displaying older posts for too long.

First, to query your most-commented posts:

‘comment_count’,’order’ => ‘desc’, ‘posts_per_page’ => ‘5’));
if($popular_posts->have_posts()) : while ($popular_posts->have_posts) : $popular_posts->the_post(); ?>


This will display the five posts from your blog with the most comments. However, if the same five posts always have the most comments, this list can get stagnant, and fast. To make sure the posts linked are always relatively new, you can also add a filter to your functions.php to restrict the length of time posts can appear in this list.

The below code goes in the functions.php file:

function filter_where($where = ”) {
$where .= ” AND post_date > ‘” . date(‘Y-m-d’, strtotime(‘-60 days’)) . “‘”;
return $where;
In this example, we’re restricting posts to ones published in the last 60 days, but you can increase or decrease the duration.

Next, call the filter right before the most popular posts are queried, and remove it at the end; just to be safe, you can also reset your WordPress query, as we’ve done in the below example:

[crayon lang=”php”]
‘comment_count’,’order’ => ‘desc’, ‘posts_per_page’ => ‘8’));
if($popular_posts->have_posts()) : while ($popular_posts->have_posts) : $popular_posts->the_post(); ?>


This is a quick and easy way to highlight the posts that are generating a lot of discussion, and to encourage others to add their two cents!

Leave a Comment

Note: Fields marked with a * are required; email addresses are not published.

Legal FAQ Collections