Orderby Multiple Meta Keys
-
I’m trying to order my posts by multiple meta keys. I have an event start date and an event start time. I want to first sort by the date and then sort within those dates by the start time.
Is there a way to do this either via the core within the functions.php file or a plugin? I noticed that I could do this if I were to first sort by title, then by a meta key…but no such luck doing it with more than one meta key.
Thanks for any insight 🙂
-
BUMP! I’m also looking for a solution to this.
I just ran into the same question. I have come up with two optons that might get you pointed in the right direction.
EDIT: Just check out Multiple Custom Field Handling under the WP_Query Class Reference
Before finding this, I tried:
Option 1:
First: Do a query, ordering by only the first meta key, and while looping through the results, save the post ID’s to an array, like:
$firstPostIDs[] = $post->ID;
THEN: Do a second query, ordering by only the second meta key and include the array of IDs from your first in post__not_in like so:$args = array( 'post_type' => 'monkeys', 'orderby' => 'meta_value', 'meta_key' => 'Age', 'post__not_in' => $firstPostIDs );
Option 2:
check out Jamie Oastler’s get_post_meta_multiple function and Matt Varone’s follow up post Query Post And Pages With Multiple Meta Values NOTE: This seems not NOT work in 3.1 or higher.That’s all I got so far…
The problem lies in here, suppose two meta keys “begindate” and “begintime”, then the meta_query argument becomes:
meta_query' => array( 'relation' => 'OR', // Begintime is "optional" array( 'key' => 'begindate' ), array( 'key' => 'begintime' ))
But only way to
orderby
meta key is using"orderby" => "meta_value"
, huh? How could I say that orderby first begindate and then begintime?
- The topic ‘Orderby Multiple Meta Keys’ is closed to new replies.