rest_get_route_for_taxonomy_items()
云策文档标注
概述
rest_get_route_for_taxonomy_items() 函数用于获取指定分类法的 REST API 路由路径。它基于分类法的配置(如 show_in_rest、rest_namespace 和 rest_base)生成带前导斜杠的路径,并可通过过滤器进行自定义。
关键要点
- 函数接受一个必需参数 $taxonomy(字符串),表示分类法名称。
- 返回值为字符串,是带前导斜杠的 REST API 路由路径,若分类法不存在或未启用 REST API 则返回空字符串。
- 内部逻辑:先通过 get_taxonomy() 获取分类法对象,检查 show_in_rest 属性;然后使用 rest_namespace(默认 'wp/v2')和 rest_base(默认分类法名称)构建路径。
- 提供过滤器 'rest_route_for_taxonomy_items',允许在返回前修改路由路径。
代码示例
// 示例:获取 'category' 分类法的 REST API 路由
$route = rest_get_route_for_taxonomy_items( 'category' );
// 可能返回:'/wp/v2/categories'注意事项
- 确保分类法已通过 show_in_rest 启用 REST API,否则函数返回空字符串。
- 函数自 WordPress 5.9.0 版本引入,使用时需注意版本兼容性。
原文内容
Gets the REST API route for a taxonomy.
Parameters
$taxonomystringrequired-
Name of taxonomy.
Source
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 );
}
Hooks
- apply_filters( ‘rest_route_for_taxonomy_items’, string $route, WP_Taxonomy $taxonomy )
-
Filters the REST API route for a taxonomy.
Changelog
| Version | Description |
|---|---|
| 5.9.0 | Introduced. |