WordPress REST API order by meta_value

Another quick tip here, for future reference.

I needed to sort the custom posts in a REST API response by a meta value, something like this:

https://www.timrosswebdevelopment.com/wp-json/wp/v2/accommodation?orderby=number_of_beds

Where number_of_beds is a field that has been added using Advance Custom Fields.

The problem is the REST API only allows certain core fields to be used for the orderby param. See my other post on adding REST API orderby custom values for more info. So the question was how to add another.

The answer came as usual on StackExchange, from here, and here. But only properly understood it after I read through the discussion a WordPress ticket.

By making use of a filters specific to my custom post type, I can set the correct query arg in the WP_Query, which makes the results return in the correct order.

Then, to orderby a meta_value, the WP_Query needs to have two values, the orderby=meta_value and also needs to have the meta_key=number_of_beds so the query knows which meta value to look at. The filter I used to achieve this is rest_{$this->post_type}_query. I look for the orderby param on the request and then set the value correctly in the query args.

In this example, I’m using meta_value_num because the value is actually a number stored as a string, so the orderby needs to take that in to account. Check out the WP_Query docs for more info on that.

NB. I originally tried to do this directly in the REST API request, like this:

https://www.timrosswebdevelopment.com/wp-json/wp/v2/accommodation?orderby=meta_value_num&meta_key=number_of_beds

But the meta_key parameter was removed and didn’t make it in to the query args. The way I have discussed was the easiest way I found to implement, only affecting one custom post type.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.