Skip to content

Instantly share code, notes, and snippets.

@rileypaulsen
Created August 19, 2014 16:08
Show Gist options
  • Save rileypaulsen/9b4505cdd0ac88d5ef51 to your computer and use it in GitHub Desktop.
Save rileypaulsen/9b4505cdd0ac88d5ef51 to your computer and use it in GitHub Desktop.
Add Advanced Custom Fields Fields to the WP REST API
function wp_api_encode_acf($data,$post,$context){
$data['meta'] = array_merge($data['meta'],get_fields($post['ID']));
return $data;
}
if( function_exists('get_fields') ){
add_filter('json_prepare_post', 'wp_api_encode_acf', 10, 3);
}
@heidipowers
Copy link

Thank you!

@mehmoodak
Copy link

The given solution didn't work for me on WordPress 5.2 but this works.

/**
 * Create REST field of ACF values for WordPress REST API
 */
function create_acf_fields_key_for_rest_api() {
	register_rest_field(
		[ 'post', 'page' ], // add post types here
		'acf_fields', // name of the field
		array(
			'get_callback'    => 'get_acf_fields_for_api',
			'update_callback' => null,
			'schema'          => null,
		)
	);
}
add_action( 'rest_api_init', 'create_acf_fields_key_for_rest_api' );

/**
 * Get ACF fields of the current post for the REST API field
 *
 * @param array $object post object array
 * @return array acf fields related to current post
 */
function get_acf_fields_for_api( $object ) {
	$data = get_fields( get_the_ID() );
	return $data ?: false;
}

@ThomasDK81
Copy link

@mehmoodak: Thank you :)

@albertoavv
Copy link

I am trying to send a post to my post type and it gives me an error, I am using custom field, help please, thank you
image

@mehmoodak
Copy link

@albertoavv The REST route you are giving isn't correct. I didn't work with ACF REST API so please read their docs carefully. By the way I also thinks that in your path wp/wp5/wp-json should be changed to wp/wp-json

@albertoavv
Copy link

Thank you for your response, if what happens is that w5 is the name of the project or the root, but thanks for your response I will continue looking for a solution,

Regards

@DonDi1989
Copy link

DonDi1989 commented Jan 20, 2020

@mehmoodak thnx for your solution. Do you have any suggestion to specify only which ACF fields do you want to retrieve or not ?

@estebanmunchjones2019
Copy link

great contribution @rileypaulsen! thanks. it works

@gmatta01
Copy link

Thanks @mehmoodak !

@ZeldOcarina
Copy link

Thank you so much @mehmoodak !

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment