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
相关产品推荐
相关产品推荐

