Get most commented posts of the week

October 22, 2008 · Print This Article

To achieve this hack, we have to make a custom SQL query by using the $wpdb object. Let’s start by creating 3 php variables: The first one is the number of days between today and X days ago, the second is today’s date and the last one is today’s date – X days.
$days = 7; //To fetch posts published during the last 7 days
$today = date("Y-m-d H:i:s"); //Today's date
$daysago = date("Y-m-d H:i:s",strtotime(date('Y-m-j H:i:s')) - (7 * 24 * 60 * 60)); //Today - $days

$result = $wpdb->get_results("SELECT comment_count,ID,post_title, post_date FROM $wpdb->posts WHERE post_date BETWEEN $daysago AND $today ORDER BY comment_count DESC LIMIT 0 , 10");

foreach ($result as $topten) {
$postid = $topten->ID;
$title = $topten->post_title;
$commentcount = $topten->comment_count;
if ($commentcount != 0) {
<li><a href="<?php echo get_permalink($postid); ?>"><?php echo $title ?></a></li>
<?php }

You can paste this code wherever you want, to get the 10 most commented posts from the last 7 days.

Your choice for site templates and wordpress themes


Got something to say?

You must be logged in to post a comment.