/var/log

Get custom post type by custom taxonomy on the WordPress rest api

To get custom post types and filter them by custom taxonomies, you can do the following:

/custom_post_type?custom_taxonomy=1

or filter by more than one taxonomy (this means: give me posts from taxonomy 1 OR 3 OR 6):

/custom_post_type?custom_taxonomy=1,3,6

or to exclude posts with specific taxonomies:

/custom_post_type?custom_taxonomy_exclude=1,5

Maybe good to know: combining categories and tags means AND, so for example the next URl means "give me posts that have categories 1 OR 2 AND also have tag 5":

/custom_post_type?categories=1,2&tags=5

It is not possible with the default api to filter on custom taxonomies by using the slug name. For this to work, you can install the filter plugin or you have to write some code that uses the rest_{$this->post_type}_query filter.

add_filter('rest_custom_post_type_query',
 'my_plugin_rest_query_filter', 10, 2);

function my_plugin_rest_query_filter($args, $request) {
 if (!empty($request['custom_taxonomy_slug'])) {
 $args['tax_query'] = [
 'taxonomy' => 'custom_taxonomy',
 'field' => 'slug',
 'terms' => $request['custom_taxonomy_slug']
 ]
 }
 return $args;
}
Tag: | Category: