Support

Account

Home Forums General Issues wp_query how to order events by date then time Reply To: wp_query how to order events by date then time

  • Ok, so I’ve solved this but not by using meta_query but by sorting the array of events after the query.

    I added a new entry to my events array called “datetime”.

        if( get_field('all_day_event', $event_item->ID) != true ):
    
          $events[$i]['datetime'] = date_format($start_date, "Y-m-d") . ' ' . get_field('start_time', $event_item->ID);
    
          $events[$i]['time'] = get_field('start_time', $event_item->ID) . ( get_field('end_time', $event_item->ID) ? ' - ' . get_field('end_time', $event_item->ID) : '' );
    
        else:
    
          $events[$i]['datetime'] = date_format($start_date, "Y-m-d") . ' 0:00';
    
          $events[$i]['time'] = null;
    
        endif;

    I then sorted the events array by using the below.

      $compare_function = function($a,$b) {
        $a_timestamp = strtotime($a['datetime']); // convert a (string) date/time to a (int) timestamp
        $b_timestamp = strtotime($b['datetime']);
            // new feature in php 7
        return $a_timestamp <=> $b_timestamp;
      };
    
      usort($events, $compare_function);