How to include ACF fields in WordPress REST API response?

The Advanced Custom Fields is a WordPress plugin that allows us to add extra content fields to WordPress. These extra content fields are more commonly knows as Custom Fields.

In many cases, we may need to expose these custom fields to the WordPress REST API response. Exposing custom fields added by ACF is quite easy. ACF has different filters for this.

Expose ACF fields for post type:

Let say we have added some custom fields to the WordPress post. Following is the code to expose the custom fields added by ACF to the WordPress REST API.

function acf_to_rest_post_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_post', 'acf_to_rest_post_api', 10, 3);

Expose ACF fields for user type:

Let say we have added some custom fields to the WordPress user. Following is the code to expose the custom fields added by ACF to the WordPress REST API.

function acf_to_rest_user_api( $response, $user, $request ) {
    if ( ! function_exists( 'get_fields' ) ) {
        return $response;
    }

    if ( isset( $user ) ) {
        $acfUser = get_fields( 'user_' . $user->ID );
        $response->data['acf'] = $acfUser;
    }

    return $response;
}
add_filter( 'rest_prepare_user', 'acf_to_rest_user_api', 10, 3 );

Expose ACF fields for page type:

Let say we have added some custom fields to the WordPress page. Following is the code to expose the custom fields added by ACF to the WordPress REST API.

function acf_to_rest_page_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_page', 'acf_to_rest_page_api', 10, 3);
Reference: