0

I have some 'Events' custom post types. On the home page of my site, I'd like to show the last X events, but in ascending order of time (earliest first). Where I am stuck is that to get the "last X" entries, I need to put the event date field in DESC order in the SQL, but after those posts are retrieved, I need to order them in ascending order.

// get posts
$posts = get_posts(array(
    'post_type'         => 'events',
    'posts_per_page'    => 2,
    'meta_key'          => 'from_datetime',
    'orderby'           => 'meta_value',
    'order'             => 'DESC'
));

Here from_datetime is my custom field using ACF. This works. It gets me the last two events. But they're in descending order of time, which means the further event is first.

Is there a way to get the last 2 events, but in ascending order of time from get_posts itself, without resorting to some array or something from the results?

1 Answer 1

0

Have you tried the last parameter with ASC like 'order => 'ASC' ? I think it will solve your problem. So your full code will be like-

// get posts
$posts = get_posts(array(
    'post_type'         => 'events',
    'posts_per_page'    => 2,
    'meta_key'          => 'from_datetime',
    'orderby'           => 'meta_value',
    // Here is the main trick happening.
    'order'             => 'ASC'
));

Hope that helps.

1
  • Yes, this is how I had it before. But because of ASC, this gives me events that have already passed. So if I could somehow bar those entries from the above query. I found something online using WP_Query which had some variation called "after" a certain date. Is there any way to limit the get_posts to only posts after now?
    – PKHunter
    Commented Feb 6, 2017 at 2:41

Your Answer

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

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