Skip to content

Instantly share code, notes, and snippets.

@MelMacaluso
Created June 4, 2019 22:54
Show Gist options
  • Star 27 You must be signed in to star a gist
  • Fork 8 You must be signed in to fork a gist
  • Save MelMacaluso/6c4cb3db5ac87894f66a456ab8615f10 to your computer and use it in GitHub Desktop.
Save MelMacaluso/6c4cb3db5ac87894f66a456ab8615f10 to your computer and use it in GitHub Desktop.
Automatically expose all the ACF fields to the Wordpress REST API in Pages and in your custom post types.
<?php
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' );
@felipelenin
Copy link

Can someone help me out here? Why is ['acf-field-group','acf-field'] the value for $postypes_to_exclude = ['acf-field-group','acf-field']?

Hi there, because is the array of post_types to exclude that can be expanded as needed, if you don't do that (comment it out or make it an empty array) check what happens :)

Hi, my code is the same problem.
But i forgete this field "Show in REST API" in settings you need set to "YES".

So is done, thanks

@easaw
Copy link

easaw commented Oct 6, 2022

I was wondering if there was a way to filter this to only show some of the fields (per post type)?

Thank you

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment