Skrevet d. 1. november 2021 af Lennart Christensen

Create fields of ACF values for Taxonomy and custom post types for WordPress REST API.

/**
 * Create REST field of ACF values for WordPress REST API
 */
function create_acf_keys_for_rest_api() {
	register_rest_field(
		[], // add post types or custom taxes in the array
		'my_fields', // name of the field in the rest
		array(
			'get_callback'    => 'get_fields_for_api',
			'update_callback' => null,
			'schema'          => null,
		)
	);
}
add_action( 'rest_api_init', 'create_acf_keys_for_rest_api' );


/**
 * Get fields of the current post for the REST API field
 * @return fields related to current object
 */
function get_fields_for_api( $object ) {
	$id  = (isset($object['taxonomy'])) ? $object['taxonomy'] . "_" . $object['id'] : $object['id'];
	$data = get_fields( $id );
	return $data ?: false;
}