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

WP REST API如何仅返回自定义文章对应的自定义分类术语名称

问题原因

你当前代码的核心问题是在get_book_type回调中直接覆盖了传入的当前文章对象$object,并且用get_terms无筛选查询了book_type分类下的所有术语,没有和当前请求的文章做关联。

回调函数的第一个入参$object本身就是当前请求的单篇文章数据,你可以通过$object['id']拿到当前文章ID,再用WordPress内置的wp_get_post_terms查询该文章关联的分类术语即可。

修改后完整代码

add_action( 'rest_api_init', 'register_book_type' );
function register_book_type() {
    register_rest_field( 'lesson',
        'book_type',
        array(
            'get_callback'    => 'get_book_type',
            'update_callback' => null,
            'schema'          => null,
        )
    );
}
function get_book_type( $object, $field_name, $request ) {
    $name = [];
    // 直接查询当前文章关联的book_type分类术语
    $terms = wp_get_post_terms( $object['id'], 'book_type' );
    foreach ( $terms as $term ) :
        array_push( $name, $term->name );
    endforeach;
    return implode( '/ ', $name );
}

调整说明

  • 没有覆盖回调传入的文章对象$object,保留了当前文章ID的获取路径
  • 替换get_terms为wp_get_post_terms,传入当前文章ID作为筛选条件,只会返回该文章绑定的分类术语
  • 移除了原来术语名称后多余的空格,避免拼接后出现不必要的空白字符

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 00:45:04