[WORDPRESS API] How to Get Featured Image from WordPress REST API (ok)

https://medium.com/@dalenguyen/how-to-get-featured-image-from-wordpress-rest-api-5e023b9896c6

How to Get Featured Image from WordPress REST API

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

Last updated