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
.
post_date
. That's why I am talking aboutdate_query
, and why I don't mention custom fields. I use theNo Future Posts
plugin.future
, so you need to change your post status parameter then'order' => 'ASC'