Advanced Custom Fields (ACF) in WP-API 2.0

There are a lot of examples on the web that explain how you can add fields defined by the Advanced Custom Fields plugin into your WP-API output. They do work properly, but most of the examples are targeting version 1 of the WP-API.

Adding the logic to WP-API version 2 is not that hard, but you need to take into account a small difference in the way the filters work.

Version 1 of the WP-API has the same kind of filters as version 2, only the prefix is different as already announced on the introduction of version 2.

json_prepare_post

VS

rest_prepare_post

Changing that is of course not an issue, it’s the data in the first 2 arguments that are passed is what you need to be aware of. In case of version 1, these are just a plain PHP arrays. In version 2 the first is an object instance of WP_REST_Response and the second a WP_Post. Writing into that object as if it’s an array will crash the PHP execution. So to give you and idea how you can transition your code see them side by side below.

Version 1

function addCustomField($data, $post, $context) {
    $data['acf'] = get_field('your-custom-field', $post['ID']);
    return $data;
}
add_filter('json_prepare_post', 'addCustomField', 10, 3);

Version 2

function addCustomField($response, $post, $request) {
    $response->data['acf'] = get_field('your-custom-field', $post->ID);
    return $response;
}
add_filter('rest_prepare_post', 'addCustomField', 10, 3);

This strategy can also be applied on pages, terms, taxonomies & users.

Happy coding!

4 Comments