Expose Chosen ACF Fields in the REST API
Adds an "acf_fields" property with the ACF fields you list to the REST API responses of chosen post types, for headless front ends and apps.
Opens WPIDE on
Code
// Post types and the field names to expose.
$wpide_acf_rest_types = array( 'post', 'page' );
$wpide_acf_rest_fields = array( 'subtitle', 'price' );
add_action( 'rest_api_init', function () use ( $wpide_acf_rest_types, $wpide_acf_rest_fields ) {
register_rest_field( $wpide_acf_rest_types, 'acf_fields', array(
'get_callback' => function ( $object ) use ( $wpide_acf_rest_fields ) {
$post_id = isset( $object['id'] ) ? (int) $object['id'] : 0;
$values = array();
if ( ! $post_id || ! function_exists( 'get_field' ) || ( ! is_post_publicly_viewable( $post_id ) && ! current_user_can( 'read_post', $post_id ) ) ) {
return $values;
}
foreach ( $wpide_acf_rest_fields as $name ) {
$values[ $name ] = get_field( $name, $post_id );
}
return $values;
},
'schema' => array(
'description' => 'Selected ACF field values.',
'type' => 'object',
'context' => array( 'view', 'edit' ),
'readonly' => true,
),
) );
} );
Notes
Only the listed fields are shared, and only for posts the visitor may read. ACF's own "Show in REST API" option exposes whole field groups instead.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.