Show Most Commented Posts in Last One Week

The more the comments in a post the more it proves the popularity and engagement in that post. Your blog readers definitely get benefited if you show post depending on comments count. You can show most commented posts in last 7 days below the single post page or in sidebar widget area. If you are searching for this kind of solution then you came to right place. Follow the steps and establish the query in your blog to show most commented posts in last one week or seven days.

In our example we have applied the code in single.php file as we want to show the list under single post page. Add the following code just below the single post loop:

[html]

<?php
$weekstart = date(‘Y-m-d’, strtotime(‘-7 days’));
$query = $wpdb->prepare("
SELECT comment_post_id, count( comment_post_id ) AS c, SUBSTRING( comment_date, 1, 10 ) AS d
FROM $wpdb->comments
WHERE (comment_date >= %s)
GROUP BY comment_post_id
ORDER BY c DESC , d DESC
",$weekstart);
$col_ids = $wpdb->get_col($query);
if ($col_ids) {
$postids = implode($col_ids,’, ‘);

function filter_orderby($orderby = ”) {
global $postids;
$orderby = " FIELD(ID,$postids )";
return $orderby;
}

add_filter(‘posts_orderby’, ‘filter_orderby’);

$args=array(
‘post__in’ => $col_ids,
‘caller_get_posts’=>1
);
$my_query = null;
$my_query = new WP_Query($args);
if( $my_query->have_posts() ) {
echo ‘<h3>List of Most Commented Posts in last 7 days</h3><ul>’;
while ($my_query->have_posts()) : $my_query->the_post(); ?>
<li> <a href="<?php the_permalink() ?>" title="<?php the_title_attribute(); ?>"><?php the_title(); ?></a>
</a></li>
<?php
endwhile;
} echo'</ul>’;
remove_filter(‘posts_orderby’, ‘filter_orderby’);
wp_reset_query(); 
}
?>

[/html]

See the action in front-end:

Show Most Commented Posts in Last One Week

 

Please leave your comment below if you like the query.

Author: mytutorialguru

Share This Post On

Submit a Comment

Your email address will not be published. Required fields are marked *