Jerry
Jerry

Reputation: 1109

Exclude exposed ACF endpoint from WP REST API

I'm using below snippet to expose my Advanced Custom Fields (ACF) to the WP REST API. This pulls approximately 700 fields into the API, when I really just need one (acf.product_description_rows.product_row_type)

Is it a way to filter the ACF Fields and only include one?

add_action( 'rest_api_init', 'bsd_register_acf_with_api' );
function bsd_register_acf_with_api() {
 if (!function_exists('get_fields')) return;

 register_rest_field(
 'product',
 'acf',
  array(
  'get_callback' => 'bsd_add_acf_fields',
  )
 );
}

function bsd_add_acf_fields( $object, $field_name, $request ) {
 $acf = get_fields( $object['id'] );
 return $acf;
 }

Upvotes: 0

Views: 829

Answers (2)

polevaultweb
polevaultweb

Reputation: 36

TL;DR - ACF now has support for the WP REST API

Hey all, Iain the Product Manager for Advanced Custom Fields here 👋

As part of the ACF 5.11 release we added native support for ACF fields in the WordPress REST API. Read more about that here.

This also allows you to filter which fields to expose the REST API.

Upvotes: 1

j0ste
j0ste

Reputation: 385

Changing function bsd_add_acf_fields() like this should do it:

function bsd_add_acf_fields( $object, $field_name, $request ) {
  $acf = get_field( 'product_row_type', $object['id'] );
  return $acf;
}

Btw you can use the plugin ACF to REST API instead.

Upvotes: 0

Related Questions