WordPress query to display most commented articles over X days

I’m creating a wordpress widget to display the most commented articles over the last 4 days.

I have this so far

Read More
global $wpdb;
global $pagepost;


function filter_where( $where = '' ) {
    // posts in the last 4 days
    $where .= " AND post_date > '" . date('Y-m-d', strtotime('-4 days')) . "'";
    return $where;
}

add_filter( 'posts_where', 'filter_where' );
$the_query = new WP_Query( 'posts_per_page=4;orderby=comment_count' );

remove_filter( 'posts_where', 'filter_where' );
?>
    <ul>
    <?php while ( $the_query->have_posts() ) : $the_query->the_post();
    echo "<li>";
    echo "<a href='".get_permalink()."' class='linkTitle'>";
    echo get_the_title();
    echo "</a>";
    woo_post_meta(); 
    echo "<div class='fix'>";
    echo "</li>";   
 endwhile;
    echo "</ul>";
wp_reset_postdata();

Which from what I can find on the wordpress site should return the articles from the last 4 days ordered by comment_count

but it’s just showing me my last 4 articles, I’m sure I’m doing something very obviously wrong here but I can’t get it

I want the 4 articles with the most comments where the article was posted in the last 4 days.

someone please save what little hair I have left

Related posts

Leave a Reply

2 comments

  1. Thanks to @swapnesh I found the answer.

    My query wasn’t correct, it should have been like this

        $the_query = new WP_Query(array( 'posts_per_page' => 4, 'orderby' => 'comment_count', 'order'=> 'DESC' ));
    
  2. $querystr = ”
    SELECT $wpdb->posts.* FROM $wpdb->posts WHERE 1=1 AND $wpdb->posts.post_status = ‘publish’ AND $wpdb->posts.post_type = ‘post’ ORDER BY $wpdb->posts.comment_count DESC
    “;

    Use this custom query

    $pageposts = $wpdb->get_results($querystr, OBJECT);
    echo’

    '; print_r($pageposts); echo'

    ‘;