函数文档

rest_get_route_for_term()

💡 云策文档标注

概述

rest_get_route_for_term() 函数用于获取指定分类法术语的 REST API 路由路径。它接受术语 ID 或 WP_Term 对象作为参数,返回带前导斜杠的路由字符串,若无法获取则返回空字符串。

关键要点

  • 参数:$term,必需,可以是整数类型的术语 ID 或 WP_Term 对象。
  • 返回值:字符串,表示术语的 REST API 路由路径,格式为“/taxonomy_route/term_id”,若无路由则返回空字符串。
  • 内部逻辑:首先通过 get_term() 获取 WP_Term 对象,然后调用 rest_get_route_for_taxonomy_items() 获取分类法路由,最后拼接术语 ID。
  • Hook:应用了 rest_route_for_term 过滤器,允许开发者自定义路由路径。

代码示例

function rest_get_route_for_term( $term ) {
    $term = get_term( $term );

    if ( ! $term instanceof WP_Term ) {
        return '';
    }

    $taxonomy_route = rest_get_route_for_taxonomy_items( $term->taxonomy );
    if ( ! $taxonomy_route ) {
        return '';
    }

    $route = sprintf( '%s/%d', $taxonomy_route, $term->term_id );

    /**
     * Filters the REST API route for a term.
     *
     * @since 5.5.0
     *
     * @param string  $route The route path.
     * @param WP_Term $term  The term object.
     */
    return apply_filters( 'rest_route_for_term', $route, $term );
}

注意事项

  • 函数在 WordPress 5.5.0 版本中引入。
  • 相关函数包括 rest_get_route_for_taxonomy_items()、get_term() 和 apply_filters()。
  • 被多个 REST API 控制器(如 WP_REST_Terms_Controller)用于准备链接。

📄 原文内容

Gets the REST API route for a term.

Parameters

$termint|WP_Termrequired
Term ID or term object.

Return

string The route path with a leading slash for the given term, or an empty string if there is not a route.

Source

function rest_get_route_for_term( $term ) {
	$term = get_term( $term );

	if ( ! $term instanceof WP_Term ) {
		return '';
	}

	$taxonomy_route = rest_get_route_for_taxonomy_items( $term->taxonomy );
	if ( ! $taxonomy_route ) {
		return '';
	}

	$route = sprintf( '%s/%d', $taxonomy_route, $term->term_id );

	/**
	 * Filters the REST API route for a term.
	 *
	 * @since 5.5.0
	 *
	 * @param string  $route The route path.
	 * @param WP_Term $term  The term object.
	 */
	return apply_filters( 'rest_route_for_term', $route, $term );
}

Hooks

apply_filters( ‘rest_route_for_term’, string $route, WP_Term $term )

Filters the REST API route for a term.

Changelog

Version Description
5.5.0 Introduced.