WP REST API Get Featured Image With Custom Endpoint

By | May 16, 2017

WP REST API Get Featured Image by adding custom endpoint in WP REST API JSON response

At previous post I already posted two ways to get featured image / post thumbnail in WP REST API call posts. Now I will write about an alternative method how to get featured image in a post by adding custom endpoint in WP REST API response.

Write this following code into your theme function then save.

add_action( 'rest_api_init', 'add_thumbnail_to_JSON' );
function add_thumbnail_to_JSON() {
//Add featured image
register_rest_field( 'post',
    'featured_image_src', //NAME OF THE NEW FIELD TO BE ADDED - you can call this anything
    array(
        'get_callback'    => 'get_image_src',
        'update_callback' => null,
        'schema'          => null,
         )
    );
}

function get_image_src( $object, $field_name, $request ) {
    $feat_img_array = wp_get_attachment_image_src($object['featured_media'], 'thumbnail', true);
    return $feat_img_array[0];
}

After that you can try to call a post by id or by slug then see the JSON response code. If it’s worked you should see a field named “featured_image_src” in your response.

I prefer to use this method to get featured image ( post thumbnail ) than the previous method because this way not showing unnecessary fields so we can make our API request load faster.

Related Posts

wp rest api v2

WP REST API Get Posts By Category

WordPress REST API tutorial get posts by category id with php script

wp rest api v2

WP REST API Get Post By Id With PHP

WordPress WP REST API V2 Tutorial get post by post id using php script.

wp rest api v2

WP REST API Get Posts By Tag

Wordpress WP REST API Tutorial Get Posts By Tag with php script

wp rest api v2

WP Rest API V2 Introduction

WP Rest API V2 Introduction. WordPress is one of the most used content management system (CMS) in the world.

wp rest api v2

Disable WP Rest API V2

Disable Wordpres WP JSON – WP Rest API V2 with and without plugin