如何在页面和自定义 postypes 中向 Wordpress REST API 公开所有 ACF 字段 [英] How to expose all the ACF fields to Wordpress REST API in both pages and custom postypes

查看:18
本文介绍了如何在页面和自定义 postypes 中向 Wordpress REST API 公开所有 ACF 字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将属于页面或自定义帖子类型的所有 ACF 字段公开给 WordPress REST API,以便通过 javascript 进行一些 API 调用.

I want to expose all the ACF fields that belong to a page or custom post type to the WordPress REST API in order to do some API calls through javascript.

最终的预期结果将是您可以轻松访问的 ACF 对象中的所有 ACF 字段.

The final expected result would be all the ACF fields inside an ACF object that you can easily access.

推荐答案

通过以下代码,您将能够在 wordpress REST API 中公开 page 和自定义 postypes ACF 字段并访问它们ACF 对象内部.

Through the following code, you will be able to expose page and your custom postypes ACF fields in the wordpress REST API and access them inside the ACF object.

您显然可以自定义要排除或包含在数组中的位置类型:$postypes_to_exclude$extra_postypes_to_include.

You can obviously customise the postypes to exclude or to include in the arrays: $postypes_to_exclude and $extra_postypes_to_include.

function create_ACF_meta_in_REST() {
    $postypes_to_exclude = ['acf-field-group','acf-field'];
    $extra_postypes_to_include = ["page"];
    $post_types = array_diff(get_post_types(["_builtin" => false], 'names'),$postypes_to_exclude);

    array_push($post_types, $extra_postypes_to_include);

    foreach ($post_types as $post_type) {
        register_rest_field( $post_type, 'ACF', [
            'get_callback'    => 'expose_ACF_fields',
            'schema'          => null,
       ]
     );
    }

}

function expose_ACF_fields( $object ) {
    $ID = $object['id'];
    return get_fields($ID);
}

add_action( 'rest_api_init', 'create_ACF_meta_in_REST' );

以下是供参考的要点:https://gist.github.com/MelMacaluso/6c4cb395f616a87>

Here's the gist for reference: https://gist.github.com/MelMacaluso/6c4cb3db5ac87894f66a456ab8615f10

这篇关于如何在页面和自定义 postypes 中向 Wordpress REST API 公开所有 ACF 字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆