2

I'm want to get posts from the last 30days in a sidebar but I don't want to use query_posts, is there a way to achieve this with the get posts function?

2 Answers 2

5

Yes, simple add a filter before you call it and remove it after you do

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

add_filter('posts_where', 'filter_where_wpa89154');
$args = array(
    'posts_per_page'  => 5,
    'post_type'       => 'post',
    'post_status'     => 'publish',
    'suppress_filters' => false
); 
$posts = get_posts($args);
remove_filter('posts_where', 'filter_where_wpa89154');

notice the 'suppress_filters' => false which is what makes this happen with get_posts

2
7

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',
    'post_status'     => 'publish',
    'date_query' => array(
        'after' => date('Y-m-d', strtotime('-30 days')) 
    ),
    'suppress_filters' => false
); 
$posts = get_posts($args);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.