[Wordpress] Ordering query results by multiple meta keys
11 Jan 2016
Ordering things with a Wordpress query is usually quite simple. Let’s say you have that good old custom post type called ‘Book’, and each book has a meta field for storing its page count. Storing additionnal data using meta keys is a common thing, most of the time using ACF in my case.
Let’s say you want to order books by page counts, then by title. You only have to add an ‘orderby’ parameter to the query :
Now let’s add another meta field to ‘Books’ : we want to store the word count this time. How can we order our books by page count, word count, then title ?
Unfortunately, i figured out the ‘meta_key’ and ‘meta_value_num’ parameters are not allowing array values, and you guess that it’s not accepting comma separated values either.
I finally came across that Wordpress Trac entry, just to discover that Wordpress was patched in 4.2 with what will help us here. Finally, you just have to use meta_queries, and give them a key name. Then use these key names in an ‘orderby’ parameter. Voilà !