Halloween Sale 15% off Ends in See the plans
PHP

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.

Don’t have WPIDE yet? Install it on your site

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

  1. Install WPIDE on your WordPress site (it is free) and open Code Snippets.
  2. Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
  3. It is added inactive: review the code and settings, then switch it on.

Have a snippet worth sharing?

Publish it to the library from WPIDE or right here. Sign in with any WordPress site that runs WPIDE, free or Pro. Public snippets are reviewed by the WPIDE team before they appear.

Which site should get this snippet?

Enter the address of your WordPress site. WPIDE opens there in a new tab with the snippet ready to review and save.

Remembered in this browser only, so you are asked once.

Report this snippet

Tell the WPIDE team what is wrong: broken code, something harmful, spam or copied work.