Is it possible to order posts by two meta values?

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?

Read More

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,

Related posts

Leave a Reply

2 comments

  1. 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
    ";