如何在页面和自定义 postypes 中将所有 ACF 字段公开给 Wordpress REST API

问题描述 投票:0回答:4

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

最终的预期结果将是您可以轻松访问的

ACF
对象中的所有 ACF 字段。

php wordpress advanced-custom-fields wordpress-rest-api
4个回答
35
投票

另一个简单的解决方案,现在非常适合我。 您可以在

functions.php
fields.php
上添加以下功能 在发送休息请求之前使用 ACF
getFields
。您可以将此添加到任何特殊页面
rest_prepare_page
rest_prepare_post
.

ACF 数据将在带有键

acf

的 json 响应中
// add this to functions.php
//register acf fields to Wordpress API
//https://support.advancedcustomfields.com/forums/topic/json-rest-api-and-acf/

function acf_to_rest_api($response, $post, $request) {
    if (!function_exists('get_fields')) return $response;

    if (isset($post)) {
        $acf = get_fields($post->id);
        $response->data['acf'] = $acf;
    }
    return $response;
}
add_filter('rest_prepare_post', 'acf_to_rest_api', 10, 3);

17
投票

通过以下代码,您将能够在 wordpress REST API 中公开

page
和您的自定义 postypes ACF 字段,并在
ACF
对象中访问它们。

您显然可以自定义要排除或包含在数组中的 postypes:

$postypes_to_exclude
$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/6c4cb3db5ac87894f66a456ab8615f10


3
投票

ACF 从 5.11 版开始能够通过每个字段将字段添加到 REST API。您可以在此处查看更新:https://www.advancedcustomfields.com/resources/rest-api/

要点是每个字段都有一个“在 REST API 中显示”的设置。默认情况下,它设置为“否”,但如果您将其切换为“是”,它将被添加到每个帖子/自定义帖子类型的 REST 数据中。


1
投票

您可以使用以下插件在 REST 中公开 ACF 字段。

https://wordpress.org/plugins/acf-to-rest-api/

如果您的 ACF 字段有关系并且想在 rest 中也包含这些关系,您可以使用以下插件。

https://github.com/airesvsg/acf-to-rest-api-recursive

更新:ACF 有自己的设置来将 ACF 字段添加到 REST 响应。所以,你不需要使用它。

© www.soinside.com 2019 - 2024. All rights reserved.