我希望在WordPress REST API中暴露属于页面或自定义文章类型的所有ACF字段,以便通过JavaScript进行一些API调用。
最终期望的结果是将所有ACF字段放入一个名为ACF
的对象中,以便轻松访问。
我希望在WordPress REST API中暴露属于页面或自定义文章类型的所有ACF字段,以便通过JavaScript进行一些API调用。
最终期望的结果是将所有ACF字段放入一个名为ACF
的对象中,以便轻松访问。
另一个对我现在完美运作的简单解决方案。
您可以在functions.php
或fields.php
中添加以下函数
在发送rest请求之前使用ACF {{link1:getFields
}}。您可以将其添加到任何特殊页面rest_prepare_page
或rest_prepare_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') && isset($post->id)) {
$response->data['acf'] = get_fields($post->id);
}
return $response;
}
add_filter('rest_prepare_post', 'acf_to_rest_api', 10, 3);
rest_prepare_cpt
。 - PattyOK页面
和自定义内容类型的ACF字段,并在ACF
对象内访问它们。$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