14

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.

Henrik Petterson
  • 6,862
  • 20
  • 71
  • 155

2 Answers2

45

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);
esamatti
  • 18,293
  • 11
  • 75
  • 82
Kode
  • 696
  • 7
  • 7
2

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' );
Lepidosteus
  • 11,779
  • 4
  • 39
  • 51
  • I cannot understand how to integrate this solution to my current code. I have updated my question with my full code, can you kindly have a look and demonstrate how your solution would work with my code? If it does work, I will certainly accept this answer as correct. – Henrik Petterson Jun 07 '13 at 23:57
  • 1
    @HenrikPetterson: my solution would stay pretty much the same with your full code. What you do is 1 - define a custom filter which does what you want (the "filter_where()" function in my answer, which limit to the last ten days), 2 - add the filter to all queries from now on using add_filter, 3 - run the query, the get_post() will call wp_query() which will apply your filter, 4 - remove the filter with remove_filter(), so it is not applied to other queries that will/might follow. The only change would be to rename $query to $posts. – Lepidosteus Jun 08 '13 at 00:04
  • You know I understood the solution just as I posted that comment. Great answer. Accepted. – Henrik Petterson Jun 08 '13 at 00:05