Date Queries in WordPress 3.7

Complex date queries in WordPress have been problematic. You couldn’t pass your date parameters along with a WP_Query except the basic ‘year’ and ‘month’ mentions. To do complex queries between dateranges you needed two filters (and thus two functions) to set and unset the extra query parameters.

It’s very surprising this has been ignored for so long, but in 2011 Alex Mills started to change that by submitting a ticket to the WordPress-core trac. Now, after 2 years of open-source development the new Date Query has finally been committed to core.

This means that come WordPress 3.7 it will be very easy to query posts based on date (which will make writing event or agenda plugins very easy, for instance). To show you how powerful this is, Alex has posted some examples:

// Get the 10 most recent posts made
// between 9AM and 5PM on weekdays
$some_posts = new WP_Query( array(
    'date_query' => array(
        array(
            'hour' => 9,
            'compare' => '>=',
        ),
        array(
            'hour' => 17,
            'compare' => '<=',
        ),
        array(
            'dayofweek' => array( 2, 6 ),
            'compare' => 'BETWEEN',
        ),
    ),
    'posts_per_page' => 10,
) );
 
// Get all posts from this summer
// June 1st to August 31st, inclusive
// Note that strtotime()-compatible strings can be used
$some_posts = new WP_Query( array(
    'date_query' => array(
        array(
            // String via strtotime()
            'after'     => 'June 1st, 2013',
            // Or if you want, an array
            'before'    => array(
                'year'  => 2013,
                'month' => 8,
                'day'   => 31,
            ),
            'inclusive' => true,
        ),
    ),
    'posts_per_page' => -1,
) );
 
// Any posts made over a year ago
// but modified in the past month
$some_posts = new WP_Query( array(
    'date_query' => array(
        array(
            'column' => 'post_date_gmt',
            'before' => '1 year ago',
        ),
        array(
            'column' => 'post_modified_gmt',
            'after'  => '1 month ago',
        )
    ),
    'posts_per_page' => -1,
) );

 

This is al pretty exciting and I can’t wait for WordPress 3.7…

  • Never miss a post…

    Spam sucks; we won't share your e-mailaddress ever

0 Reacties

Laat een reactie achter

Uw email zal niet zichtbaar zijn

*