7

I'm trying to write a WP_Query where I'm calling only posts that have been posted after march 2012. I can successfully call posts that are just in March 2012, but struggling to do 'from March 2012 onwards'.

    $current_year = date('2012');
    $current_month = date('>3'); // This doesn't work
    $current_month = date('3'); // This DOES work

    $custom_query = new WP_Query("year=$current_year&monthnum=$current_month&order=ASC&posts_per_page=-1");

Am I missing something simple, or does this have to get more complicated?

2 Answers 2

17

Since WordPress version 3.7, there's the WP_Query argument date_query that works perfectly for this type of query.

As you can see in the Codex, you can specify a date query with the after argument. The after can either be a strtotime()-compatible string, or an array of 'year', 'month', 'day' values.

For your example, something like the following should work:

$args = array(
    'posts_per_page' => -1,
    'date_query'     => array(
        'after' => array(
            'year'  => 2012,
            'month' => 3,
            'day'   => 1,
        ),
    ),
);
$custom_query = new WP_Query( $args );

Or with a strtotime()-string:

$args = array(
    'posts_per_page' => -1,
    'date_query'     => array( 'after' => '2012-03-01' ),
);
$custom_query = new WP_Query( $args );
2
  • you can also include the after date into the query by adding 'inclusive' => true otherwise only the posts from the 2nd will be included
    – Aaron
    Jan 21, 2021 at 12:36
  • Use the after date_query like alisspers says with strtotime() function like so: strtotime('-3 day') or strtotime('-2 week') or strtotime('next Thursday') Read about more options in PHP's docs: php.net/manual/es/function.strtotime.php May 11, 2021 at 20:53
8

The "Time Parameters" section in http://codex.wordpress.org/Class_Reference/WP_Query has a note about date ranges. Using the same technique:

$query_string = "order=ASC&posts_per_page=-1";

// Create a new filtering function that will add our where clause to the query
function filter_where( $where = '' ) {
    $where .= " AND post_date >= '2012-03-01'";
    return $where;
}

add_filter( 'posts_where', 'filter_where' );
$custom_query = new WP_Query( $query_string );
remove_filter( 'posts_where', 'filter_where' );
0

Your Answer

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

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