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

WP REST API:获取文章接口返回分类名称而非ID的方案咨询

解决WordPress REST API返回分类名称而非ID的方案

当然有办法搞定这个需求!我在开发中经常遇到开发者需要调整REST API的返回字段,下面分享两种实用的方案:

方案一:使用API内置的_embed参数(无需写代码)

WordPress的REST API自带了嵌入关联资源的功能,只需要在请求URL末尾加上?_embed参数,就能获取到分类的完整信息(包括名称、slug等),而不只是ID。

比如原本的请求是:
/wp-json/wp/v2/posts/:post_id

修改后变成:
/wp-json/wp/v2/posts/:post_id?_embed

返回结果里会多出一个_embedded字段,其中wp:term数组下的第一个元素就是该文章的分类数据,你可以从中提取name字段拿到分类名称。举个简单的提取示例(假设用JavaScript):

// 假设response是API返回的结果
const categoryNames = response._embedded['wp:term'][0].map(item => item.name);
console.log(categoryNames); // 输出分类名称数组

方案二:自定义修改REST响应(适合需要直接整合到主字段的场景)

如果希望分类名称直接出现在返回的主数据里,而不是嵌套在_embedded中,可以通过添加自定义代码实现。在你的主题functions.php文件中加入以下代码:

add_filter('rest_prepare_post', 'add_category_names_to_rest_response', 10, 3);
function add_category_names_to_rest_response($response, $post, $request) {
    // 获取文章的分类ID列表
    $category_ids = wp_get_post_categories($post->ID);
    $category_names = [];
    
    // 遍历分类ID,获取对应的分类名称
    foreach ($category_ids as $id) {
        $category = get_category($id);
        if ($category) {
            $category_names[] = $category->name;
        }
    }
    
    // 将分类名称添加到响应数据中
    $response->data['category_names'] = $category_names;
    
    return $response;
}

添加这段代码后,再次请求/wp-json/wp/v2/posts/:post_id,返回的结果里就会多出一个category_names字段,直接包含该文章的所有分类名称数组。

两种方案各有优势:方案一快速无需编码,适合前端直接处理;方案二更灵活,能自定义字段名和展示方式,适合需要后端统一输出格式的场景。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 03:46:35