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.
The final expected result would be all the ACF fields inside an ACF
object that you can easily access.
To retrieve a field value as a variable, use the get_field() function. This is the most versatile function which will always return a value for any type of field. To display a field, use the the_field() in a similar fashion.
To export Advanced Custom Fields, go to WP All Export › New Export and select the post type or custom post type attached to your ACF fields. Set up the export using drag & drop, then process the export and proceed to download the export file.
Another simple solution that is working perfect for me now.
You can add the following function on functions.php
or fields.php
Using ACF getFields
before sending a rest request. You can add this to any special page rest_prepare_page
or rest_prepare_post
.
The ACF data will be in the json response with key 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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With