Php 如何在页面和自定义PostType中向Wordpress REST API公开所有ACF字段
我想将属于页面或自定义post类型的所有ACF字段公开给WordPress REST API,以便通过javascript进行一些API调用Php 如何在页面和自定义PostType中向Wordpress REST API公开所有ACF字段,php,wordpress,advanced-custom-fields,wordpress-rest-api,Php,Wordpress,Advanced Custom Fields,Wordpress Rest Api,我想将属于页面或自定义post类型的所有ACF字段公开给WordPress REST API,以便通过javascript进行一些API调用 最终的预期结果将是ACF对象中的所有ACF字段,您可以轻松访问这些字段。通过以下代码,您将能够在wordpress REST API中公开页面和自定义postypes ACF字段,并在ACF对象中访问它们 显然,您可以自定义要排除或包含在数组中的postypes:$postypes\u to\u exclude和$extra\u postypes\u to
最终的预期结果将是
ACF
对象中的所有ACF字段,您可以轻松访问这些字段。通过以下代码,您将能够在wordpress REST API中公开页面
和自定义postypes ACF字段,并在ACF
对象中访问它们
显然,您可以自定义要排除或包含在数组中的postypes:$postypes\u to\u exclude
和$extra\u postypes\u to\u 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' );
以下是参考要点:您可以使用以下插件公开REST中的ACF字段 如果您的ACF字段具有关系,并且希望在rest中也包含这些关系,则可以使用以下插件
另一个简单的解决方案现在对我来说非常适合。 您可以在
functions.php
或fields.php
在发送rest请求之前使用ACF。您可以将其添加到任何特殊页面rest\u prepare\u page
或rest\u prepare\u post
ACF数据将在json响应中,键为ACF
// 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);
让我们知道你到目前为止都做了些什么。。给我们看一些代码。@cbdev420嗨,我创建这个问题只是为了帮助其他在黑暗中跌跌撞撞的开发人员,我自己回答(见下文)。谢谢,我知道这些插件,过去也使用过它们。不幸的是,它们很容易与主要(但也有次要)WordPress更新中断。代码片段太多了,但是稍微少了一点,因为它使用的是核心的香草WordPress函数!请注意,对于自定义贴子类型(cpt),过滤器是
rest\u prepare\u cpt
您就是一个图例。非常感谢您提供的解决方案没有插件或黑客。