ADVERTISEMENT

Wordpress - WP Rest API - How to get featured image

You can get it without plugins by adding _embedas param to your query

/?rest_route=/wp/v2/posts&_embed
/wp-json/wp/v2/posts?_embed

I would NOT use the better rest API plugin. It did add featured images to the rest api but it also broke it.

This is the simplest solution I was able to find that actually worked. Add the following code to your functions.php:

<?php

function post_featured_image_json( $data, $post, $context ) {
  $featured_image_id = $data->data['featured_media']; // get featured image id
  $featured_image_url = wp_get_attachment_image_src( $featured_image_id, 'original' ); // get url of the original size

  if( $featured_image_url ) {
    $data->data['featured_image_url'] = $featured_image_url[0];
  }

  return $data;
}
add_filter( 'rest_prepare_post', 'post_featured_image_json', 10, 3 );


You can get the name of the image with this path:

array_name._embedded['wp:featuredmedia']['0'].source_url