首页 > 解决方案 > 为wordpress rest api公开acf的所有字段

问题描述

我在 wordpress 网站中使用高级自定义字段。我创建了一个在帖子中使用的自定义字段。然后我为主页创建了一个自定义字段(关系字段),以便我可以从那里选择帖子。当我为我的主页进行 api 调用时,我看到了带来帖子的 acf,但我看不到帖子中使用的 acf。如何公开所有字段以将它们与我的 api 一起使用?它应该是这样的

{
acf: {
relationship_field: [
{
id: 5,
post_content: "something...",
...
acf: {
...
},
...
}
]
}
}

我看不到嵌套的 acf(我不知道实际上是否应该这样,但你明白了)。提前致谢。

标签: wordpressapiadvanced-custom-fieldswordpress-rest-api

解决方案


如果我理解正确,您应该调用register_rest_field以便在获取帖子时将额外数据添加到响应中。


register_rest_field('post', '_embedded', array(
            'get_callback' => function ($post) {
                return [
                    'field_1' => get_field('field_xxxxxxxxxxxxx', $post['id']),
                    'field_2' => get_field('field_xxxxxxxxxxxxx', $post['id']),
                ];
            }
        ));

推荐阅读