Get the next event using date_query

I created a CPT called event and want to make a query to show the next future event, based on it’s publish date.

Here is the WP_Query args:

$today = getdate();
$args = array(
    'post_status' => array('publish', 'future'),
    'post_type' => 'event',
    'orderby' => 'date',
    'order' => 'ASC',
    'posts_per_page' => 1,
    'date_query' =>
        array(
            array(
                'year'  => $today['year'],
                'compare'   => '>=',
            ),
            array(
                'month' => $today['mon'],
                'compare' => '>=',
            ),
            array(
                'day' => $today['mday'],
                'compare' => '>=',
            )
        )
);

It’s work fine when there is event in the current month. But now, the next event is on april, and the script don’t show anything.

SOLUTION

$args = array(
    'post_status' => array('publish', 'future'),
    'post_type' => 'event',
    'orderby' => 'date',
    'order' => 'ASC',
    'posts_per_page' => 1,
    'date_query' =>
        array(
            'after' => 'today'
        )
);

1 Answer
1

I am not sure without running which query precisely this results in, but I don’t think it is intended format for such query.

If you take a look at Date Parameters documentation, there is a special case of after and before when you want to find posts in some direction from specific point.

Leave a Comment