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 thoughts on “Advanced Custom Fields (ACF) in WP-API 2.0”

  1. Hi,
    You can also use the plugin “ACF to WP REST API”.
    http://wordpress.org/plugins/acf-to-wp-rest-api

    The plugin supports the types: post, user, term, comment, attachment and options.

    You can also manipulate the answers using the filter “acf_to_wp_rest_api_{type}_data”, where the wildcard “{type}” may be the types mentioned above.

    How to use:
    add_filter( ‘acf_to_wp_rest_api_post_data’, function( $data ) {
    //manipulate your data here
    return $data;
    }, 10, 3);

    1. I don’t exactly get what you mean. This works on any type, because a custom post type is nothing more then a plain post, only identified by a different ‘type’ name.

Leave a Reply

Your email address will not be published. Required fields are marked *