0

I have created a custom post type in Wordpress and exposed it to rest API. I have also added custom fields to this post using the ACF plugin.

In my themes function.php I have registered these fields in the response and I can see them when I make a get request.

register_rest_field('auto', 'specs', array('get_callback' => 'get_autos_specs_for_api'));

The problem is that when I send a post request, wordpress doesn't recognize these fields. It creates a new post with the title and all the extra fields are empty.

Yasin Yaqoobi
  • 1,888
  • 3
  • 27
  • 38

3 Answers3

0

Try that solution:

function wp_api_encode_acf($data,$post,$context){
    $data['meta'] = array_merge($data['meta'],get_fields($post['ID']));
    return $data;
}

if( function_exists('get_fields') ){
    add_filter('json_prepare_post', 'wp_api_encode_acf', 10, 3);
}

Refer: https://gist.github.com/rileypaulsen/9b4505cdd0ac88d5ef51

softbrewery
  • 501
  • 6
  • 18
0

For me what did the trick was to hook yourself to the rest prepare post and then add your fields to the array, then return the response object.

function slug_add_data($response, $post) {

    $response->data['latitud'] = get_field('latitud', $response->data['id']);
    $response->data['longitud'] = get_field('longitud', $response->data['id']);

    return $response;
}

add_filter('rest_prepare_post', 'slug_add_data', 10, 3);
brasofilo
  • 25,496
  • 15
  • 91
  • 179
Simon Berton
  • 468
  • 5
  • 13
0

Instead of using the custom code, Use the out of the box solution for accessing ACF fields into the Rest API.
Plugin URL: https://github.com/airesvsg/acf-to-rest-api

Add the filter as below:

//Filter to to get acf field within acf field for relational field set
add_filter( 'acf/rest_api/<custom_posttype>/get_fields', function( $data ) {
    if ( ! empty( $data ) ) {
        array_walk_recursive( $data, 'get_fields_recursive' );
    }

    return $data;
} );

You will get the ACF fields object inside the default WordPress Rest API response it's self, If all configuration are correct.

Let me know if any helps needed!

Jenil Kanani
  • 369
  • 1
  • 14