WordPress如何通过WP_REST_Posts_Controller获取指定文章字段
解决方案
你当前代码返回全量文章数据,是因为调用了WP_REST_Posts_Controller的完整响应预处理逻辑,会默认输出所有文章公共字段。仅获取文章标题有两种常用实现方案:
方案1:手动组装返回数据(性能最优,推荐)
直接从查询结果中提取需要的字段,不需要调用REST控制器预处理,还可以优化数据库查询逻辑,完整修改后的代码如下:
function myspace_get_posts_by_tag(WP_REST_Request $request) { $slug = $request['slug']; $page = $request['page']; $term = get_term_by('slug', $slug, 'post_tag'); $posts_per_page = 1; $args = array( 'tag__in' => $term->term_id, 'posts_per_page' => $posts_per_page, 'paged' => $page, 'orderby' => 'date', 'order' => 'desc', // 仅查询文章ID,降低数据库查询开销 'fields' => 'ids' ); $query = new WP_Query( $args ); $max_pages = $query->max_num_pages; $total = $query->found_posts; $data = []; foreach ( $query->posts as $post_id ) { // 仅组装需要的文章标题字段 $data[] = [ 'post_title' => get_the_title($post_id) // 后续需要其他字段可直接在此处追加 ]; } $response = new WP_REST_Response($data, 200); $response->header( 'X-WP-Total', $total ); $response->header( 'X-WP-TotalPages', $max_pages ); return $response; }
该方案减少了不必要的REST响应构造逻辑,查询性能更高,适合仅需要少量字段的接口场景
方案2:从REST响应中提取指定字段
如果需要保留REST控制器自带的权限校验、字段过滤等原生逻辑,可直接从预处理后的响应结果中提取标题字段,仅需修改循环部分代码:
$controller = new WP_REST_Posts_Controller('post'); foreach ( $posts as $post ) { $response = $controller->prepare_item_for_response( $post, $request ); $response_data = $controller->prepare_response_for_collection( $response ); // 仅保留经过安全过滤的渲染后标题 $data[] = [ 'post_title' => $response_data['title']['rendered'] ]; }
如果需要未经过HTML转义的原始标题,可替换为$response_data['title']['raw'],注意raw字段仅对拥有文章编辑权限的请求用户返回
内容的提问来源于stack exchange,提问作者la_petite_kozel
相关产品推荐
相关产品推荐

