Use Advanced Custom Fields in WordPress REST API Response

Posted By: Proper Noun Staff Posted On: February 18, 2021 Share:

The Wordpress v2 API can be an extremely powerful tool when developing custom websites, web apps, or even mobile apps if you know how to wield it properly.  In our experimentation and research with the Wordpress API, one issue we ran in to was the ability to utilize the hugely popular plugin Advanced Custom Fields in the native API response. Advanced Custom Fields allows for rapid addition of new data points to just about any page or post type, so being able to include these data points in our API response would allow for a much more rapid development process. After a little bit of google-fu and tinkering, we came up with this script that can be used in the 'functions.php' file of any Wordpress install.

$post_type = "case_studies";

function case_studies_rest_prepare_post($data, $post, $request) {
$_data = $data->data;

$fields = get_fields($post->ID);
if($fields){
foreach ($fields as $key => $value){
$_data[$key] = get_field($key, $post->ID);
}

$data->data = $_data;
}
else{

}

return $data;
}

add_filter("rest_prepare_{$post_type}", 'case_studies_rest_prepare_post', 10, 3);

In this case, I have two custom post types I am exposing to the Wordpress API, 'case_studies' and 'clients'. I can now access these custom post types along with their Advanced Custom Fields via the standard Wordpress V2 API route, for example http://www.yourwebsite.com/wp-json/wp/v2/case_studies.

When it comes to utilizing your API route, one approach you can take is using cURL to request and parse the data. Once your request returns a response, you can then easily use the data in any framework you'd like, for example React or StencilJS. You can also just use the API to hook in to the WP data and plugin functionalities and run everything through a more secure, faster custom HTML5 website.

No matter the need, the Wordpress API can be used as an excellent option for content management for an MVP / bootstrap web application, mobile application, static web design project, or other R&D website development project.

Proper Noun Staff

Proper Noun Staff

In-House Writing Team

Read informative articles, insights, and other resources right from the experts on the Proper Noun team.

Copyright © Proper Noun 2024