Site icon Hip-Hop Website Design and Development

Sorting events by descending date, and ascending time if multiple events on a date

We have a listing of events that we would like to be descending by date and within a single date if there are multiple events ascending by time. Originally I tried adding an ‘AND’ relation and working with orderby as outlined in the codex in the meta_query portion of the WP_Query but that does not work because there are not separate keys for date and time so they need to be calculated from the same event_timestamp.

Since we process the query into objects that include eventDate and eventTime strings, I tried wp_list_sort with the event_timestamp and eventTime as keys to orderby (‘DESC’ and ‘ASC’ respectively) but it would only orderby the eventTimestamp. This was the last version of how I was trying that:

$sorted_past_events = wp_list_sort(
   $past_events,
   array(
     'timestampGMT' => 'DESC',
     'eventTime'    => 'ASC',
   ),
);

So now I’ve circled around to just trying to have the db do all the work and return the events sorted properly. This SQL query works in SequelPro:

SELECT p.ID, p.post_title, from_unixtime(m.meta_value,'%Y-%m-%d') as eventdate, from_unixtime(m.meta_value,'%H.%i.%s') as eventtime, m.meta_value, p.post_date, p.post_status, p.post_type
FROM wp_posts as p
JOIN wp_term_relationships as r
    ON p.ID = r.object_id
JOIN wp_postmeta as m
    ON p.ID = m.post_id
WHERE r.term_taxonomy_id = '74456'
AND m.meta_key = 'event_timestamp'
ORDER BY eventdate DESC, eventtime ASC;

And I am having trouble getting it working dropped into php. This is my current attempt:

global $wpdb;
   
$past_events_query = $wpdb->get_results(
        $wpdb->prepare(
        "SELECT p.ID, p.post_title, m.meta_value = %s as eventdate, m.meta_value = %s as eventtime, m.meta_value, p.post_date, p.post_status, p.post_type
        FROM wp_posts as p
        JOIN wp_term_relationships as r
            ON p.ID = r.object_id
        JOIN wp_postmeta as m
            ON p.ID = m.post_id
        WHERE r.term_taxonomy_id = %d
        AND m.meta_key = 'event_timestamp'
        ORDER BY eventdate DESC, eventtime ASC;",
        gmdate( 'Y-m-d', 'event_timestamp' ),
        gmdate( 'H:i:s', 'event_timestamp' ),
        $term
    ),
);

I’m fairly certain I’ve messed up how to pass in the variables for the timestamp and the term (which we need because we are pulling only events that belong to a certain series) and am at a loss on how to debug this. Frankly if it could be made to work in the meta_query or with wp_list_sort that would be ideal. As I’m fairly new to WordPress, this site has been hugely helpful as I’ve plodded through this over the past couple of days but at this point I’m spinning my wheels.

Thank you!