How to Expose All the Acf Fields to Wordpress Rest API in Both Pages and Custom Postypes

How to expose all the ACF fields to Wordpress REST API in both pages and custom postypes

Through the following code, you will be able to expose page and your custom postypes ACF fields in the wordpress REST API and access them inside the ACF object.

You can obviously customise the postypes to exclude or to include in the arrays: $postypes_to_exclude and $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' );

Here's the gist for reference: https://gist.github.com/MelMacaluso/6c4cb3db5ac87894f66a456ab8615f10

Wordpress ACF retrieve file data from REST API

I was able to find an answer in this post: https://support.advancedcustomfields.com/forums/topic/acf-rest-api-image-only-shows-attachment-id/

Adding ?acf_format=standard to the end of my request did the trick, and that added an additional array of info beyond the ID for each file that included the URL.

Populate ACF Fields using Wordpress Rest API JS

Like the GET request, You can use the POST request as well to store data into the CMS. What you need to do is to pass the authorization headers with the POST API call.

You can get more detail about the authorization mechanism here: https://developer.wordpress.org/rest-api/using-the-rest-api/authentication/

Headers:

Authorization:Bearer <token>
Content-Type:application/json

Secondly you can pass the Body data as a RAW json as below:

{
"title":"Sample ACF field demo",
"status": "publish",
"fields":
{
"text_custom_field_name" : "Text value",
"checkbox_custom_field_name" : [
"Option1,",
"Option2,",
"Option3"
],
"textarea_custom_field_name" : "This is message field",
"boolean_custom_field_name" : [
true
]
}
}

Please let me know if any help needed.

Thanks

Update ACF fields inside layout via WP API

I found from this post that you should use the key fields instead of acf. In addition, I had to send a Content-type: application/json header to get it working.



Related Topics



Leave a reply



Submit