WordPress Rest API: filter Posts using a tax_query
Amend the default posts endpoint of the WordPress API to allow a tax_query which will return posts tagged with a given term.
The WordPress REST API is a powerful, flexible and extensible method of pushing and pulling data to and from your WordPress site. The default queries supported by the /posts endpoint, however, do not offer the kind of flexibility we are used to enjoying with WP Query.
If you find yourself needing to perform a tax_query on the posts returned by your API endpoint, the following snippet will help. In this particular example, we’re using a custom taxonomy of ‘country’ and the slug of the term in question, though this can easily be amended to work with a different term field such as ID.
The object is to allow us to return all posts tagged with Europe by making a request to:
/wp-json/wp/v2/posts?country_slug=europe
In order to do this, we need to append a tax_query to the WP query that runs on the /posts endpoint. The filter does exactly that when a request parameter named country_slug
is present:
function rest_filter_by_custom_taxonomy( $args, $request ) {
if ( isset($request['country_slug']) )
{
$country_slug = sanitize_text_field($request['country_slug']);
$args['tax_query'] = [
[
'taxonomy' => 'country',
'field' => 'slug',
'terms' => $country_slug,
]
];
}
return $args;
}
add_filter('rest_post_query', 'rest_filter_by_custom_taxonomy', 10, 3);