如何在页面和自定义样式中将所有ACF字段公开给Wordpress REST API [英] How to expose all the ACF fields to Wordpress REST API in both pages and custom postypes
问题描述
我想将属于页面或自定义帖子类型的所有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
和自定义的笔迹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' );
这里是要参考的要点:>://gist.github.com/MelMacaluso/6c4cb3db5ac87894f66a456ab8615f10 >
Here's the gist for reference: https://gist.github.com/MelMacaluso/6c4cb3db5ac87894f66a456ab8615f10
这篇关于如何在页面和自定义样式中将所有ACF字段公开给Wordpress REST API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!