Wordpress Rest API - Custom Fields

梦想与她 提交于 2019-12-12 05:59:10

问题


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.


回答1:


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




回答2:


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);




回答3:


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!



来源:https://stackoverflow.com/questions/44233659/wordpress-rest-api-custom-fields

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!