REST API: Support custom namespaces for taxonomies.

While a taxonomy can define a custom route by using the rest_base argument, a namespace of wp/v2 was assumed. This commit introduces support for a rest_namespace argument.

A new rest_get_route_for_taxonomy_items function has been introduced and the rest_get_route_for_term function updated to facilitate getting the correct route for taxonomies.

For maximum compatibility sticking with the default wp/v2 namespace is recommended until the API functions see wider use.

Props spacedmonkey.
Fixes #54267.
See [51962].


git-svn-id: https://develop.svn.wordpress.org/trunk@51964 602fd350-edb4-49c9-b593-d223f7449a82
This commit is contained in:
Timothy Jacobs
2021-11-01 03:26:06 +00:00
parent 9ca3e8f36b
commit 2cd084aeb0
9 changed files with 127 additions and 35 deletions
+36 -15
View File
@@ -3115,24 +3115,12 @@ function rest_get_route_for_term( $term ) {
return '';
}
$taxonomy = get_taxonomy( $term->taxonomy );
if ( ! $taxonomy ) {
$taxonomy_route = rest_get_route_for_taxonomy_items( $term->taxonomy );
if ( ! $taxonomy_route ) {
return '';
}
$controller = $taxonomy->get_rest_controller();
if ( ! $controller ) {
return '';
}
$route = '';
// The only controller that works is the Terms controller.
if ( $controller instanceof WP_REST_Terms_Controller ) {
$namespace = 'wp/v2';
$rest_base = ! empty( $taxonomy->rest_base ) ? $taxonomy->rest_base : $taxonomy->name;
$route = sprintf( '/%s/%s/%d', $namespace, $rest_base, $term->term_id );
}
$route = sprintf( '%s/%d', $taxonomy_route, $term->term_id );
/**
* Filters the REST API route for a term.
@@ -3145,6 +3133,39 @@ function rest_get_route_for_term( $term ) {
return apply_filters( 'rest_route_for_term', $route, $term );
}
/**
* Gets the REST API route for a taxonomy.
*
* @since 5.9.0
*
* @param string $taxonomy Name of taxonomy.
* @return string The route path with a leading slash for the given taxonomy.
*/
function rest_get_route_for_taxonomy_items( $taxonomy ) {
$taxonomy = get_taxonomy( $taxonomy );
if ( ! $taxonomy ) {
return '';
}
if ( ! $taxonomy->show_in_rest ) {
return '';
}
$namespace = ! empty( $taxonomy->rest_namespace ) ? $taxonomy->rest_namespace : 'wp/v2';
$rest_base = ! empty( $taxonomy->rest_base ) ? $taxonomy->rest_base : $taxonomy->name;
$route = sprintf( '/%s/%s', $namespace, $rest_base );
/**
* Filters the REST API route for a taxonomy.
*
* @since 5.9.0
*
* @param string $route The route path.
* @param WP_Taxonomy $taxonomy The taxonomy object.
*/
return apply_filters( 'rest_route_for_taxonomy_items', $route, $taxonomy );
}
/**
* Gets the REST route for the currently queried object.
*