Order by meta_value_num DESC and meta_value ASC on WP 4.0

Although the new orderby parameter is great in WP_Query, it does not support multiple orderby for multiple meta_key‘s.

I’ve went through a couple of scenarios and even went and digged into trac and make and came up with the following

None of the issues regarding this very problem have been answered. It also seems from those two links that there is an issue ordering by a meta_key and another field like post date for instance. I haven’t tried this as yet.

I truelly think that you have two choices here without creating two queries.

  • hack using the posts_orderby filter as described by @s_ha_dum in his answer here

  • By making use of PHP ordering using usort. The idea here would be to sort your query by one meta_key and then take the returned posts array ($posts) and sort them by the second meta_key before the loop starts. You can either use the the_posts filter (just remember to remove the filter once done) or simply unset $posts in your template and set it with the reordered array of posts once done

Leave a Comment