最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin4浏览0评论

UPDATE: Solved with the answer below.

$past_events     = array();
$past_events_sql = $wpdb->get_results(
    $wpdb->prepare(
        "SELECT p.ID, from_unixtime(m.meta_value,'%%Y-%%m-%%d') as eventdate, from_unixtime(m.meta_value,'%%H.%%i.%%s') as eventtime, p.post_title, 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'
        AND from_unixtime(m.meta_value) < CURRENT_TIMESTAMP
        ORDER BY eventdate DESC, eventtime ASC;",
        $term->term_taxonomy_id,
        ),
    );

Original question:

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:

global $wpdb;
   
$past_events_query = $wpdb->get_results(
        $wpdb->prepare(
        "SELECT p.ID, from_unixtime(m.meta_value,'%%Y-%%m-%%d') as eventdate, from_unixtime(m.meta_value,'%%H.%%i.%%s') as eventtime, p.post_title, 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;",
        $term-term_taxonomy_id
    ),
    OBJECT,
);

The obstacle now is even when adding the argument to return an OBJECT (which is the default for get_results) it's returning an array. Is there a way to handle this? 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!

发布评论

评论列表(0)

  1. 暂无评论