WordPress REST API – add Featured Image to ACF relationship post object

You’ve set up a relationship field with Advanced Custom Fields (ACF), but you need the selected post and it’s Featured Image? 

Say no more fam! I gotcha!

surprised reaction

The following snippet shows how you can add the Featured Image to the post object that’s returned with the relationship field in Advanced Custom Fields (ACF).

add_filter( 'acf/rest_api/{type}/get_fields', function ( $item, $request ) {

	if ( isset( $item['acf']['your-field-name'] ) ) {
		foreach( $item['acf']['your-field-name'] as $key => $relation ) {
			$relation_id = $relation->ID;

			$featured = wp_get_attachment_image_src( get_post_thumbnail_id( $relation->ID ), 'full' );

			if ( $featured ) $item['acf']['relationship'][$key]->featured_image = $featured[0];
		}
	}

	return $item;
}, 10, 2 );