All ACF Fields to Custom Post Type

A long time ago, I put a post up about getting ACF Fields for a custom post type in the WP JSON API response but you’d have to do that one by one. Sometimes that would be good but if you have a lot of fields and don’t mind them being public it’s not so good.

So I was looking around and hit this StackOverflow question. This is a nice option for getting all the fields . . . as long as you remember to change the filter name to be rest_prepare_YOURCUSTOMPOSTYPENAME then it’ll work for any custom post type. Otherwise you’ll think it doesn’t work.

function acf_to_rest_api($response, $post, $request) {
    if (!function_exists('get_fields')) return $response;

    if (isset($post)) {
        $acf = get_fields($post->id);
        $response->data['acf'] = $acf;
    }
    return $response;
}
add_filter('rest_prepare_YOURCUSTOMPOSTYPTEHERE', 'acf_to_rest_api', 10, 3);//if you leave it as post, it's just for posts