How to Get Featured Image from WordPress REST API

Dale Nguyen
Mar 30, 2018 · 1 min read

There is a time when I have to get a featured image from WordPress REST API. It’s quite strange that the first place when REST API document doesn’t return the featured image by default which is something that should have done in first place.

Luckily, there are few ways that you can get the featured image after calling the REST API.

Method 1: Use Better REST API featured images plugin. I don’t recommend to use this plugin unless you are super lazy.

Method 2: Add ?_embed at the end of the URL. Take a look at the example below

https://example.com/wp-json/wp/v2/posts?_embed

Your featured image is in:

[your-data]._embedded['wp:featuredmedia']['0'].source_url

Method 3: Add featured image directly to REST API. You can do it by editing functions.php file or creating a plugin for this. (Credit to my boss :D)

add_action('rest_api_init', 'register_rest_images' );function register_rest_images(){
register_rest_field( array('post'),
'fimg_url',
array(
'get_callback' => 'get_rest_featured_image',
'update_callback' => null,
'schema' => null,
)
);
}
function get_rest_featured_image( $object, $field_name, $request ) {
if( $object['featured_media'] ){
$img = wp_get_attachment_image_src( $object['featured_media'], 'app-thumb' );
return $img[0];
}
return false;
}

I will update frequently uses wordpress snippets to my git: https://github.com/dalenguyen/wordpress-snippets

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store