如何让WordPress JSON API返回分类法的slug或名称而非ID?
解决WordPress REST API返回分类名称/Slug替代ID的方案
方法1:为目标接口添加额外字段
在主题functions.php或自定义插件中插入代码,给to_book类型的REST响应追加分类的名称或Slug字段:
add_action( 'rest_api_init', 'add_taxonomy_details_to_to_book' ); function add_taxonomy_details_to_to_book() { // 添加ba_language的Slug字段 register_rest_field( 'to_book', 'ba_language_slug', array( 'get_callback' => function( $post ) { $terms = wp_get_post_terms( $post['id'], 'ba_language' ); return wp_list_pluck( $terms, 'slug' ); }, 'schema' => array( 'description' => 'ba_language分类的Slug', 'type' => 'array', 'items' => array( 'type' => 'string' ) ), ) ); // 添加ba_language的名称字段 register_rest_field( 'to_book', 'ba_language_name', array( 'get_callback' => function( $post ) { $terms = wp_get_post_terms( $post['id'], 'ba_language' ); return wp_list_pluck( $terms, 'name' ); }, 'schema' => array( 'description' => 'ba_language分类的名称', 'type' => 'array', 'items' => array( 'type' => 'string' ) ), ) ); }
方法2:直接替换原ID字段返回内容
如果希望彻底替换原ba_language字段的ID输出,可通过过滤器修改响应数据:
add_filter( 'rest_prepare_to_book', 'replace_taxonomy_id_with_details', 10, 3 ); function replace_taxonomy_id_with_details( $response, $post, $request ) { $terms = wp_get_post_terms( $post->ID, 'ba_language' ); // 替换为Slug,若要名称则替换为wp_list_pluck($terms, 'name') $response->data['ba_language'] = wp_list_pluck( $terms, 'slug' ); return $response; }
方法3:创建自定义REST端点
若无法修改原接口代码,可新建自定义端点整合数据:
add_action( 'rest_api_init', 'custom_to_book_api_endpoint' ); function custom_to_book_api_endpoint() { register_rest_route( 'custom/v1', '/to_book', array( 'methods' => 'GET', 'callback' => 'fetch_to_book_with_taxonomy_details', ) ); } function fetch_to_book_with_taxonomy_details( $request ) { $posts = get_posts( array( 'post_type' => 'to_book', 'posts_per_page' => -1, ) ); $output = array(); foreach ( $posts as $post ) { $base_data = get_post( $post->ID, ARRAY_A ); $language_terms = wp_get_post_terms( $post->ID, 'ba_language' ); $base_data['ba_language_slug'] = wp_list_pluck( $language_terms, 'slug' ); $base_data['ba_language_name'] = wp_list_pluck( $language_terms, 'name' ); $output[] = $base_data; } return rest_ensure_response( $output ); }
方法4:前端临时映射(无后端权限时用)
如果无法修改后端,可在前端完成ID到名称/Slug的映射:
async function getToBookWithLanguageInfo() { const [toBookResp, langResp] = await Promise.all([ fetch('/wp-json/wp/v2/to_book'), fetch('/wp-json/wp/v2/ba_language') ]); const toBookList = await toBookResp.json(); const languageList = await langResp.json(); const langMap = languageList.reduce((map, lang) => { map[lang.id] = { slug: lang.slug, name: lang.name }; return map; }, {}); return toBookList.map(item => { if (item.ba_language) { item.ba_language = item.ba_language.map(id => langMap[id].slug); // 若要名称则替换为 langMap[id].name } return item; }); }
内容的提问来源于stack exchange,提问作者omar al aufi
相关产品推荐
相关产品推荐

