How to Get Featured Image from WordPress REST API


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 using 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 the functions.php files 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;
}

Leave a comment