From your comments:
I just wanted to find out if there was a core endpoint for listing
custom taxonomies with associated post type records.
And as I said in my original answer: (slightly modified, though)
The endpoint in question is a taxonomy term endpoint which returns
the data (e.g. description, name and slug) for a specific term, but
the response does not include posts in that term because posts have
their own endpoints (e.g./wp/v2/your_post_type?experiences=7
to get
posts of theyour_post_type
type in the customexperiences
taxonomy for term with the ID 7), but only if the post type is
enabled in the REST
API
So no, there is no core endpoint that works out-of-the-box like regular term archive pages like one at example.com/category/uncategorized
, example.com/?cat=1
or example.com/experiences/foo-bar
(where experiences
is a custom taxonomy slug), which by default displays posts from all or any post types associated with the taxonomy of the requested term.
I was hoping I could get this from one endpoint
Perhaps a custom end point would be better in this case
Yes, that’s an easy way as opposed to making multiple API requests for the different post types associated with your taxonomy, and it also saves you from possibly having to do complex JS coding for dealing with paging.
But actually, you could just make use of the Search endpoint (/wp/v2/search
) along with the rest_post_search_query
filter to modify the search query args which will be passed to WP_Query
.
So that means, just like you can control the main WordPress query via the pre_get_posts
hook, you can also control the Search endpoint query via the above filter.
So you can add taxonomy queries, meta queries, etc.
And here’s an example that you can try, where you would make a request to /wp/v2/search?type=post&<taxonomy slug>=<term ID or slug>
, e.g. /wp/v2/search?type=post&experiences=7
or /wp/v2/search?type=post&experiences=term-slug
.
Notes:
-
The
type=post
above must always be that and it’s not a post type! Instead, it means you’re searching for posts. -
In the response, the actual post type (slug) is in the property named
subtype
.
add_filter( 'rest_post_search_query', 'my_rest_post_search_query', 10, 2 );
function my_rest_post_search_query( $query_args, $request ) {
$tax_query = array();
$post_types = array();
$tax_objects = get_taxonomies( array(
'publicly_queryable' => true,
), 'objects' );
foreach ( $tax_objects as $taxonomy => $tax_object ) {
if ( ! empty( $request[ $taxonomy ] ) ) {
$tax_query[] = array(
'taxonomy' => $taxonomy,
'terms' => $request[ $taxonomy ],
'field' => is_numeric( $request[ $taxonomy ] ) ? 'term_id' : 'slug',
);
$post_types = array_merge( $post_types, (array) $tax_object->object_type );
}
}
if ( ! empty( $tax_query ) ) {
$query_args['tax_query'] = $tax_query;
$query_args['post_type'] = $post_types;
}
return $query_args;
}