I want to get the most commented posts for the last x days,I have the following code:

  global $wpdb;
  $weekstart = date('Y-m-d', strtotime('-12 days'));
  $query = $wpdb->prepare("
  SELECT comment_post_id, count( comment_post_id ) AS c, SUBSTRING( comment_date,1,    5     ) 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,', ');
 echo $postids;

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

add_filter('posts_orderby', 'filter_orderby');  

I want to filter the posts by id,the problem is that echoing $orderby (for testing) would return this: FIELD(ID, )
and not the actual order, the FIELD is not recognized and $postids is empty. What am i missing here ? How can I get this to work properly ? Thank you.

1 Answer 1


You can do this using the orderby parameter of WP_Query. If you set it to comment_count, you can get the most popular. You will probably need to filter the WHERE parameter to set your date on the query (unless you want the last week or the last month or something simple like that) though.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.