Hi – I’m setting up a little project using WordPress as a headless CM. I want to expose the data from a custom post type (movies
), which uses ACF fields (Movies), and display the data in a ReactJS App.
I got it working but I did so using a plugin called ACF to REST API which I later found out not to have been updated for the past couple of years.
I opened a ticket and asked the ACF team for an alternative solution. I was directed to the following page where a vanilla solution would be found: https://stackoverflow.com/questions/56473929/how-to-expose-all-the-acf-fields-to-wordpress-rest-api-in-both-pages-and-custom.
The code solution on offer is:
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' );
I disabled the ACF to REST API plugin and pasted the above code into functions.php
of the theme I was using.
The result was that my React App broke. Also, when I looked at the /wp-json
output the only reference to ACF was acf-disabled
.
I played around with this part of the code:
$postypes_to_exclude = ['acf-field-group','acf-field'];
$extra_postypes_to_include = ["page"];
First Try
$postypes_to_exclude = ['acf-field-group','acf-field'];
$extra_postypes_to_include = ["page", "movie"];
Second Try
$postypes_to_exclude = [];
$extra_postypes_to_include = ["page", "movie", "acf-field-group","acf-field"];
but still got the same result in /wp-json.
Should this code go in functions.php
?
How should I tweak it to make it output the ACF Movies fields in /wp-json
?
Hopefully thanking you in advance! 🙂