How to filter WordPress REST API for custom post type by taxonomy slug

I spent ages looking for an answer to my question of how to implement this, I knew that it was possible but I couldn’t seem to find the right answer anywhere. So I’m posting it here for my future reference and in case anyone else finds it.

The issue is compounded by there being so many links to old questions and tutorials for previous versions of the WordPress REST API. As of writing my version of wordpress is 4.9.8. And that makes it REST API v2.

I finally found the answer to my question here on stackexchange.


A little background

I have created a custom post type for my site of accommodation, and enabled the rest API for my custom type using the show_in_rest parameter when defining the custom post type.

I’ve also created a taxonomy called accommodation_size, and this classifies the accommodation.

Now, the part I was having trouble finding out is how to limit query results based on the taxonomy. I couldn’t find the info anywhere.

But I finally found the StackExchange post and it cleared everything up.


Example Request

To enable the filter to work, I had to add two extra args when creating the custom taxonomy.

'show_in_rest' => true, // This enables the REST API endpoint
'query_var' => true // This allows us to append the taxonomy param to the custom post api request.

Once this is done then you can call the custom post REST API, with our param.

https://www.timrosswebdevelopment.com/wp-json/wp/v2/accommodation?accommodation_category=2543

The first thing to notice here is that the parameter name is the official name of the taxonomy, NOT the slug that you define in the rewrite block.

The second take home point is that you have to specify the Term ID as the parameter value. Using the slug for the term doesn’t work.

To get the id of the term you can use the taxonomy endpoint to query it, or do it in PHP if you are serverside.

https://www.timrosswebdevelopment.com/wp-json/wp/v2/accommodation_category?slug=large

OR

$term = get_term_by('slug', 'large', 'accommodation_category');

This will return you a term id to use in your main request.


I hope that might be of help to someone in the future. It might change in future versions of the API but it works for now and that’s all that matters!

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.