get_posts no older than X days – WordPress

In my WordPress site, I use this get_posts code:

get_posts(
        array (
            'numberposts' => 5,
            'orderby'=>'comment_count',
            'order'=>'DESC',
            'post_type'   => array ( 'post' )
        )

How do I filter it so that the posts are not older than 10 days? So it should only list posts from the past 10 days.

Related posts

Leave a Reply

2 comments

  1. The exemple from the doc should work just fine. get_posts() uses WP_Query() behind the scene to make the actual request. For your case the modified example should look something like this:

    // Create a new filtering function that will add our where clause to the query
    function filter_where( $where = '' ) {
        // posts in the last 30 days
        $where .= " AND post_date > '" . date('Y-m-d', strtotime('-10 days')) . "'";
        return $where;
    }
    
    add_filter( 'posts_where', 'filter_where' );
    $query = get_posts(array (
                'numberposts' => 5,
                'orderby'=>'comment_count',
                'order'=>'DESC',
                'post_type'   => array ( 'post' )
             ));
    remove_filter( 'posts_where', 'filter_where' );