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

ACF返回Post Object时,如何使其与标准WP JSON格式一致?

解决ACF REST API返回相关文章非标准WP格式问题
  • 先检查ACF字段配置:你的「相关文章」字段得是Post Object类型,并且在字段设置里把「返回格式」改成「Post Object」(别选Post ID)。要是之前选的是ID,返回的自然不是完整对象。

  • 加PHP过滤器修正格式:直接把这段代码贴到主题的functions.php或者自定义插件里,能把ACF返回的带post_前缀的字段转换成标准WP REST格式:

add_filter('acf/rest_api/post/get_fields', 'format_related_posts_to_wp_rest', 10, 3);
function format_related_posts_to_wp_rest($fields, $post, $request) {
    if (isset($fields['related_posts']) && is_array($fields['related_posts'])) {
        $formatted_posts = [];
        foreach ($fields['related_posts'] as $related_post) {
            if ($related_post instanceof WP_Post) {
                $controller = new WP_REST_Posts_Controller($related_post->post_type);
                $response = $controller->prepare_item_for_response($related_post, $request);
                $formatted_posts[] = $controller->prepare_response_for_collection($response);
            }
        }
        $fields['related_posts'] = $formatted_posts;
    }
    return $fields;
}

这段代码会自动遍历related_posts数组,用WordPress原生的REST控制器处理每个文章对象,输出和/wp/v2/posts接口一致的标准格式。

  • 验证请求参数:前端请求里的acf_format=standard别删掉,ACF靠这个参数返回结构化字段,过滤器才能正常处理。

  • 备选方案:要是上面的方法没效果,换个思路——先从主文章接口拿到相关文章的ID数组,再单独请求/wp/v2/posts?include=ID1,ID2接口,这样拿到的就是纯标准WP Post数据,前端再把它和主文章关联起来就行。

内容的提问来源于stack exchange,提问作者J. Jackson

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 06:05:02