rest_output_link_header()
云策文档标注
概述
rest_output_link_header() 函数用于为 REST API 发送 Link 头部,以提供 API 根 URL 和当前查询资源的 JSON 链接。
关键要点
- 函数检查 headers_sent() 和 get_rest_url() 返回值,避免在头部已发送或 API 根 URL 为空时执行。
- 发送两个 Link 头部:一个指向 REST API 根 URL(rel="https://api.w.org/"),另一个指向当前查询资源的 JSON 端点(rel="alternate")。
- 使用 sanitize_url() 和 _x() 等辅助函数确保 URL 安全和字符串本地化。
代码示例
function rest_output_link_header() {
if ( headers_sent() ) {
return;
}
$api_root = get_rest_url();
if ( empty( $api_root ) ) {
return;
}
header( sprintf( 'Link: ; rel="https://api.w.org/"', sanitize_url( $api_root ) ), false );
$resource = rest_get_queried_resource_route();
if ( $resource ) {
header(
sprintf(
'Link: ; rel="alternate"; title="%2$s"; type="application/json"',
sanitize_url( rest_url( $resource ) ),
_x( 'JSON', 'REST API resource link name' )
),
false
);
}
}注意事项
- 此函数在 WordPress 4.4.0 版本中引入,需确保环境兼容。
- 依赖于多个相关函数如 rest_get_queried_resource_route() 和 get_rest_url(),调用前应确认其可用性。
- Link 头部用于 REST API 发现和资源链接,有助于客户端自动化处理 API 端点。
原文内容
Sends a Link header for the REST API.
Source
function rest_output_link_header() {
if ( headers_sent() ) {
return;
}
$api_root = get_rest_url();
if ( empty( $api_root ) ) {
return;
}
header( sprintf( 'Link: <%s>; rel="https://api.w.org/"', sanitize_url( $api_root ) ), false );
$resource = rest_get_queried_resource_route();
if ( $resource ) {
header(
sprintf(
'Link: <%1$s>; rel="alternate"; title="%2$s"; type="application/json"',
sanitize_url( rest_url( $resource ) ),
_x( 'JSON', 'REST API resource link name' )
),
false
);
}
}
Changelog
| Version | Description |
|---|---|
| 4.4.0 | Introduced. |