WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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.

share|improve this question

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.

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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