Wordpress Rest API - Custom Fields
Asked Answered
I

3

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.

Itemize answered 29/5, 2017 at 1:50 Comment(0)
S
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

Standardbearer answered 29/5, 2017 at 6:58 Comment(2)
Yeah that's the first thing I saw. I think that is for the plugin. It doesn't work with the built in wordpress API.Itemize
I understand, Why do not you try to use the default WP function to get a meta get_post_meta ?Standardbearer
R
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);
Regulus answered 11/8, 2017 at 14:4 Comment(0)
R
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!

Ranchman answered 13/9, 2019 at 10:48 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.