get_posts no older than X days - Wordpress

Henrik Petterson picture Henrik Petterson · Jun 8, 2013 · Viewed 17.7k times · Source

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.

Answer

Kode picture Kode · Jul 31, 2014

As of 3.7 you can use date_query https://developer.wordpress.org/reference/classes/wp_query/#date-parameters

So it would look like:

$args = array(
    'posts_per_page' => 5,
    'post_type' => 'post',
    'orderby' => 'comment_count',
    'order' => 'DESC',
    'date_query' => array(
        'after' => date('Y-m-d', strtotime('-10 days')) 
    )
); 
$posts = get_posts($args);