Mel*_*uso 19 php wordpress advanced-custom-fields wordpress-rest-api
我想将属于页面或自定义帖子类型的所有 ACF 字段公开给 WordPress REST API,以便通过 javascript 进行一些 API 调用。
最终的预期结果将是ACF您可以轻松访问的对象内的所有 ACF 字段。
小智 31
另一个简单的解决方案,现在对我来说很完美。在发送休息请求之前,您可以在functions.php或fields.php
Using ACF上添加以下功能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')) 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);
Run Code Online (Sandbox Code Playgroud)
Mel*_*uso 15
通过以下代码,您将能够page在 wordpress REST API 中公开您的自定义 postypes ACF 字段并在ACF对象内访问它们。
您显然可以自定义要排除或包含在数组中的 postype:$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' );
Run Code Online (Sandbox Code Playgroud)
以下是参考要点:https : //gist.github.com/MelMacaluso/6c4cb3db5ac87894f66a456ab8615f10
| 归档时间: |
|
| 查看次数: |
16770 次 |
| 最近记录: |