Sorting By Multiple Meta Keys Using WP_Query

Recently I was working on a project where I was carrying out some additional page queries and therefore using the excellent WP_Query class with WordPress. The requirements were slightly different however as there was some custom sorting needed. Here is how I utilised sorting the results of WP_Query with multiple post meta keys.

WP_Query is the heart of a more complex WordPress site build as it allows you to query different content objects in WordPress and then loop through the results to display these in your templates where you need to. Rarely do I build a site without it.

One of the arguments you can pass into WP_Query is the order and orderby parameters. Order can either be ascending  [ASC] (A – Z) or descending [DESC] (Z  – A). Orderby is the thing you want to order the posts by, either ASC or DESC by. For example you could sort posts by their title which would sort them alphabetically. You could sort them by date either oldest first or newest first.

However the site I was building required a more complex ordering approach for the results of my custom query using WP_Query. The site in question was a dance studio and I needed to get the times of classes (a post type so would return posts). The posts returned had three meta keys (amongst others) for day of the class, the start time of the class and the location or studio where the class took place. To get these to be listed correctly I needed then to be sorted by the day of the week (Monday – Sunday) and then by the class time (Earliest – Latest in the day). This way the results would look like a timetable.

Thankfully you can do this with the WP_Query class! First take a look at the code for the query below and then we can take a look at what is happening.

https://gist.github.com/wpmark/217422b4210fdd8e3c46

We see a normal WP_Query including a meta query. The difference here is that we are indexing each of the meta arrays with a name (day, location, start_time). We can then use this in the orderby argument. We pass this an array with the index being the meta array name and the value being either ASC or DESC. This now gives us posts order firstly by the meta key of _wpmark_day and next by the meta_key of _wpmark_start_time.

You can see an example of the results here – https://www.sandersondance.co.uk/studios/nelson/timetable/

Leave a Reply