WP_Query orderby multiple parameters not working

2019-09-09 22:17发布

I am trying to sort by my WP_Query results by two meta fields, first date and then time. So effectively

Date A 17:00
Date B 18:00
Date C 07:00
Date B 10:00 
Date A 9:00

would be come

Date A 9:00
Date A 17:00
Date B 10:00 
Date B 18:00
Date C 07:00

This is my current code:

"post_type" => "event",
"post_status" => "publish",
"posts_per_page" => 25,
"ignore_sticky_posts" => 0,
"show_sticky" => true,
"meta_query" => array(
    array(
    "key" => "_meta_event_start_date",
    "compare" => ">=",
    "value" => 0
    ),
    array(
    "key" => "_meta_event_start_time",
    "compare" => ">=",
    "value" => 0
    ),
),
"order" => "ASC",
"orderby" => "_meta_event_start_date _meta_event_start_time"

It is currently sorting my results appropriately by the date, but not the time (time format is stored hh:mm (24hr)). How might I amend the query to make this work?

I have seen other responses recommending using foreach loops, sql queries or even filters. I can't use these unfortunately as the site I'm working on uses the search plugin Facet WP, and as search requires WP_Query to query the database and output content.

Thanks in advance.

标签: wordpress
1条回答
你好瞎i
2楼-- · 2019-09-09 22:47

As I see you are trying to order by meta keys - you have to use in this case a quite more complicated syntax according to changes in WordPress 4.2 - something like below:

"post_type" => "event",
"post_status" => "publish",
"posts_per_page" => 25,
"ignore_sticky_posts" => 0,
"show_sticky" => true,
"meta_query" => array(
    "event_start_date" => array(
        "key" => "_meta_event_start_date",
        "compare" => ">=",
        "value" => 0
    ),
    "event_start_time" => array(
        "key" => "_meta_event_start_time",
        "compare" => ">=",
        "value" => 0
    )
),
"orderby" => array(
    "event_start_date" => "ASC",
    "event_start_time" => "ASC"
)

Additionally - for single meta_key ordering it is worth to remember that you have to use in the orderby clause values meta_value and meta_value_num

查看更多
登录 后发表回答