How to filter WP rest api json data

Add this snippet into functions.php and if you want to implement it in any custom post type then just change the filter hook name: rest_prepare_{custom_post_type}

function dandd_post_json_fields( $data, $post, $context ) {
	$image_attributes = wp_get_attachment_image_src( $data->data['featured_media'] );

	$post_categories = wp_get_post_categories( $data->data['id'] );
	$cats = array();
		
	foreach($post_categories as $c){
		$cat = get_category( $c );
		$cats[] = array( 'name' => $cat->name );
	}

    return [
        'id'          => $data->data['id'],
	'date'        => $data->data['date'],
	'link'        => $data->data['link'],
        'title'       => $data->data['title']['rendered'],
        'excerpt'     => $data->data['excerpt']['rendered'],
        'content'     => $data->data['content']['rendered'],
        'image'       => $image_attributes[0],
        'categories'  => $cats,
    ];
}
add_filter( 'rest_prepare_post', 'dandd_post_json_fields', 12, 3 );

Leave a Reply

Your email address will not be published.