rest_output_link_wp_head()
云策文档标注
概述
rest_output_link_wp_head() 函数用于在页面头部输出 REST API 链接标签,包括 API 根 URL 和当前查询对象的资源路由链接。
关键要点
- 输出 REST API 链接标签到页面头部,支持自动检测和生成相关 URL。
- 使用 get_rest_url() 获取 API 根 URL,并通过 rest_get_queried_resource_route() 获取当前查询对象的资源路由。
- 函数内部包含安全检查,如使用 esc_url() 清理 URL,确保输出安全。
代码示例
function rest_output_link_wp_head() {
$api_root = get_rest_url();
if ( empty( $api_root ) ) {
return;
}
printf( '', esc_url( $api_root ) );
$resource = rest_get_queried_resource_route();
if ( $resource ) {
printf(
'',
_x( 'JSON', 'REST API resource link name' ),
esc_url( rest_url( $resource ) )
);
}
}注意事项
- 此函数从 WordPress 4.4.0 版本开始引入,使用时需确保版本兼容性。
- 输出链接标签依赖于 REST API 功能,需确保 REST API 已启用且可访问。
- 相关函数如 get_rest_url()、rest_get_queried_resource_route() 和 esc_url() 在调用前应了解其用途和返回值。
原文内容
Outputs the REST API link tag into page header.
Description
See also
Source
function rest_output_link_wp_head() {
$api_root = get_rest_url();
if ( empty( $api_root ) ) {
return;
}
printf( '<link rel="https://api.w.org/" href="%s" />', esc_url( $api_root ) );
$resource = rest_get_queried_resource_route();
if ( $resource ) {
printf(
'<link rel="alternate" title="%1$s" type="application/json" href="%2$s" />',
_x( 'JSON', 'REST API resource link name' ),
esc_url( rest_url( $resource ) )
);
}
}
Changelog
| Version | Description |
|---|---|
| 4.4.0 | Introduced. |