You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过WordPress API仅获取嵌入数据中的作者名称?

解决方案:WordPress API 仅获取作者名称的几种方式

1. 原生API单次请求优化(减少冗余数据)

原生WordPress REST API的_fields参数不支持直接索引嵌入数组的元素(比如_embedded.author[0].name写法无效),但你可以通过指定用户端点的返回字段来大幅减少冗余。请求时搭配users_fields参数限制作者数据的返回内容:

my_site_for_example_purposes/wp-json/wp/v2/posts?_fields=id,title.rendered,link,date,author,excerpt.rendered,tags,categories,yoast_head_json.og_image&_embed=author&users_fields=name

此时返回的_embedded.author数组里只会包含name和关联必需的id,冗余信息会被大幅削减。

2. 后端添加自定义字段(推荐:单次请求直接拿作者名)

如果想要直接在文章响应里获取作者名称(无需嵌入字段),可以在主题的functions.php中添加以下代码,注册一个自定义REST字段:

add_action( 'rest_api_init', function () {
    register_rest_field( 'post',
        'author_name',
        array(
            'get_callback' => function( $post ) {
                $author = get_userdata( $post['author'] );
                return $author ? $author->display_name : '';
            },
            'schema' => array(
                'description' => '文章作者名称',
                'type' => 'string'
            ),
        )
    );
} );

添加后,你可以直接在请求中指定_fields=author_name,无需使用_embed参数:

my_site_for_example_purposes/wp-json/wp/v2/posts?_fields=id,title.rendered,link,date,author_name,excerpt.rendered,tags,categories,yoast_head_json.og_image

响应里会直接出现author_name字段,值就是作者名称,完全没有冗余数据。

3. 客户端过滤(无需改后端,简单处理)

如果不想修改后端代码,可在拿到响应后,直接在客户端提取_embedded.author[0].name的值,忽略其他冗余字段。这种方式无需额外请求,只是返回数据会包含冗余内容,但处理成本极低。

4. 单独调用作者端点(备选方案)

若以上方法都不适用,可先获取文章列表拿到作者ID,再批量调用用户端点获取名称:

my_site_for_example_purposes/wp-json/wp/v2/users?include=1647,xxx&_fields=id,name

这种方式需要两次请求,但能精准获取所需数据。


内容的提问来源于stack exchange,提问作者linguini

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 03:54:28