Archive for July 2017

Adding Advanced Custom Fields to WordPress REST API Response

There seems to be a lot of outdated information as to how to add your ACF fields into your WordPress REST API response, especially if you’re using the v2 API that’s now built into WordPress. The answer comes thanks to baptistebriel on a GitHub issue response for a plugin that seemed to work for API v1.

Here’s his code, slightly reworked.

$post_type = "post";

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

    $fields = get_fields($post->ID);

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

    $data->data = $_data;
    return $data;

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

See below, where my custom fields maturity, traits, and variety are all part of the object that’s returned from the API.