0

I'm working on displaying a listing of posts that have a an advanced custom field Date Picker, and I need to display all upcoming posts in ascending order. So far I can get the wp_query to show all upcoming posts in descending order (i,e. Dec 26 2019, Dec 13 2019, Nov 26 2019), but this is not correct. They need to be in ascending order for it to make sense to users (i.e. Nov 26 2019, Dec 13 2019, December 26 2019).

This is what I have so far that works at showing the posts in descending order based on their acf date field values:

$wp_query = new WP_Query(array(
    'post_type' => 'post',
    'cat' => 4,
    'posts_per_page' => 10,
    'paged' => $paged,
    'meta_key' => 'event_date',
    'orderby' => 'meta_value',
    'order' => 'DESC'
));
 <?php while ($wp_query->have_posts()) : $wp_query->the_post(); ?>
        <?php
        $eventDate = get_field("event_date");
        $eventTime = date("h:iA", get_field("event_time"));
        $eventLocation = get_field("event_location");
        $eventPrice = get_field("event_price");
        $blogtime = current_time('mysql');
        $blogTimeEdit = date("M d Y");

        $now_strtotime   = strtotime('now');
        $event_strtotime = strtotime($eventDate);
        ?>
    <?php if($event_strtotime > $now_strtotime): ?>
      [post html]
    <?php endif; ?>
<?php endwhile; ?>

The acf field is event_date, and I'm getting all upcoming events based on today's date vs the event_date value. It's so close to working but I need to display these posts in ascending order by event_date. If I change DESC to ASC, it doesn't work as the query returns ALL posts in ascending order, and the if statement won't show anything.

I'm not sure if there is a way to sort by event_date vs today's date AND sort the results in ascending order within the wp_query? Or maybe I need to add something to the if statement that's comparing the event_date to today's date?

  • What return format do you have set? The default is d/m/Y which wouldn't come out in the order you expect and might not be sortable. You would want "Ymd" so it's sortable, and you might then need to adjust your date comparison as strtotime() likely won't parse it in that format. – WebElaine Nov 19 '19 at 19:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.