web design blog post

Use Advanced Custom Fields in WordPress REST API Response

Posted Wednesday, July 04, 2018

Posted By Adam Hodson


Share This Content


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.

Let's Get In Touch

We love to talk about new project ideas & movie trivia.

Our Offices

300 SW 1ST Avenue, #155
Fort Lauderdale, FL 33301

Give Us A Call.

954.674.1258

Sending Message

Please wait...