JSON API to show Advanced Custom Fields - WordPress JSON API to show Advanced Custom Fields - WordPress json json

JSON API to show Advanced Custom Fields - WordPress


@Myke: you helped me tremendously. Here's my humble addition:

add_filter('json_api_encode', 'json_api_encode_acf');function json_api_encode_acf($response) {    if (isset($response['posts'])) {        foreach ($response['posts'] as $post) {            json_api_add_acf($post); // Add specs to each post        }    }     else if (isset($response['post'])) {        json_api_add_acf($response['post']); // Add a specs property    }    return $response;}function json_api_add_acf(&$post) {    $post->acf = get_fields($post->id);}


Update for Wordpress 4.7

With the release of Wordpress 4.7 the REST functionality is no longer provided as a distinct plugin, rather its rolled in (no plugin required).

The previous filters don't appear to work. However the following snippet does (can be in your functions.php):

>= PHP 5.3

add_filter('rest_prepare_post', function($response) {    $response->data['acf'] = get_fields($response->data['id']);    return $response;});

< PHP 5.3

add_filter('rest_prepare_post', 'append_acf');function append_acf($response) {    $response->data['acf'] = get_fields($response->data['id']);    return $response;};

Note the filter is a wild card filter, applied like

apply_filters("rest_prepare_$type", ...

so if you have multiple content types (custom), you will need to do:

add_filter('rest_prepare_multiple_choice', 'append_acf');add_filter('rest_prepare_vocabularies', 'append_acf');function append_acf($response) {    $response->data['acf'] = get_fields($response->data['id']);    return $response;};

Note It appears that rest_prepare_x is called per record. So if you are pinging the index endpoint, it will be called multiple times (so you don't need to check if its posts or post)


Came here by searching with the same question. This isn't totally vetted yet but I think this is getting on the right path. Check it out.

I have one less nested level than you do so this might need altered a bit. But the JSON API plugin has a filter called json_api_encode. I have a repeater called specifications that looks like this.

http://d.pr/i/YMvv

In my functions file I have this.

add_filter('json_api_encode', 'my_encode_specs');function my_encode_specs($response) {  if (isset($response['posts'])) {    foreach ($response['posts'] as $post) {      my_add_specs($post); // Add specs to each post    }  } else if (isset($response['post'])) {    my_add_specs($response['post']); // Add a specs property  }  return $response;}function my_add_specs(&$post) {  $post->specs = get_field('specifications', $post->id);}

Which appends a custom value to the JSON API output. Notice the get_field function from ACF works perfectly here for bringing back the array of the repeater values.

Hope this helps!