Question

I'm doing a WP_Query with a date_query parameter after, and I want the nearest post after that date, but I get the farest ones in the future from the date. Is there any parameter to control this? something like 'near_to' => 'past/future', or WP_Query always retrieve the most recent? This is my code:

$my_query = new WP_Query(array(
    'post_type' => 'event',
    'posts_per_page' => 1,
    'date_query' => array(
        'after' => date('Y-m-d h:i',time())
    )
));

I have an events site, and I want to show the next one, not the farest one.

Ignore the fact that the date checked is today and the post that I search for are in the future. It doesn't matter (no?).

I have been loking at the Codex but I didn't find anything. Have I to query for ALL post and the go to the last one in the $my_query->posts array?

Edit: I don't want to order my results, I want to limit them by older posts, not by newest (default). I have several posts with a future date (events), and I want the next event. If I do a query with only this parameter 'posts_per_page' => 1 I get the latest post, and I want the oldest.

Thanks!


The solution is to use the parameter 'order' => 'ASC'. Thanks to @PieterGoosen and @webtoure. Now let me explain why my question was not 100% correct, and why it works.

I didn't test with 'order' because I only have 1 wrong post (that was I thought), I had nothing to order, but WP_Query does not works that way. As I myself explained on this answer, WP_Query first finds the posts that match the criteria, and then orders them, do the pagination, etc. So you can search for posts 'after' a date (all of them), order then by 'ASC', and get only 1 post with 'posts_per_page' => 1.

Was it helpful?

Solution

Are you actually using 'after' => date('Y-m-d h:i',time()) in your code? That will always ask for posts older newer that the exact current time when that query is run. Something like this:

'after' => date( 'Y-m-d h:i', time() - 60 * 60 * 24 )

would give you a reference for 24 hours in the past.

The above part is for history's sake. The solution in this answer is and was right all along though.

As for the results being "backwords" (newest to oldest instead of vice versa) you might want to add an order clause to your snippet (I haven't tested it):

$my_query = new WP_Query( array(
    'post_type' => 'post',
    'order' => 'ASC',
    'posts_per_page' => 1,
    'date_query' => array(
        array(
            'after' => date( 'Y-m-d h:i', time() ),
        )
    ),
) );

Final edit (tested and working). You need the order clause since WordPress queries posts 'DESC' by default. Test the code and see for yourself.

Licensed under: CC-BY-SA with attribution
Not affiliated with wordpress.stackexchange
scroll top