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.

Answers


As of 3.7 you can use date_query http://codex.wordpress.org/Class_Reference/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);

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' );

Need Your Help

Measure Network Data with Python

python networking traffic-measurement

I'm currently writing a program to shut down a computer when over a period of time (say, half an hour) network traffic is below a certain threshold.

FBSOpenApplicationErrorDomain error 1

ios xcode ios-simulator swift2 xcode7

I'm trying to run my iOS app that was migrated from Swift 1.2 to Swift 2.0 in Xcode 7 using iPhone Simulator (any), I'm getting the following error: