• Hi guys,

    i’m using the following code to determine the most commented posts of the last 7 days:

    <?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');  //need this filter so posts get returned in the order we specify
    
      $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 'List of Posts with most comments in last 7 days';
        while ($my_query->have_posts()) : $my_query->the_post(); ?>
          <p><a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>"><?php the_title(); ?></a></p>
          <?php
        endwhile;
      }
      remove_filter('posts_orderby', 'filter_orderby');
      wp_reset_query();  // Restore global post data stomped by the_post().
    }
    ?>

    Source

    I was wondering if you guys could improve it a little as i don’t have the skills for it.
    For example comments marked as spam are messing up the results as their posts get counted until i delete the spam.

    Your help is very appreciated.

  • The topic ‘Most commented posts of the last 7 days’ is closed to new replies.