2

Hopefully this is a reasonably straightforward question!

Is it possible to order posts, on the front-end of my WP install, by two meta values?

I have a meta key called genus and another called species. I'd like to sort firstly by genus (ASC), then species (ASC).

Thanks in advance,

2 Answers 2

1

AFAIK, you can't do it using a meta query. Check this example, does what you want.

1
3

The simplest solution I can think of is to join the posts meta table with posts table twice. Modifying codex example a bit you can use this:

$querystr = "
SELECT wposts.* 
FROM $wpdb->posts wposts, $wpdb->postmeta wpostmeta1, $wpdb->postmeta wpostmeta2
WHERE wposts.ID = wpostmeta1.post_id
AND wposts.ID = wpostmeta2.post_id
AND wpostmeta1.meta_key = 'genus'
AND wpostmeta2.meta_key = 'species'
AND wposts.post_type = 'post'
ORDER BY wpostmeta1.meta_value ASC,
         wpostmeta2.meta_value ASC
";
1
  • +1 Thanks, this was way simpler than the link in the accepted answer. Commented Jun 29, 2012 at 0:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.