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 Media Detail By ID

WordPress WP REST API V2 get media attachment by id with php curl tutorial and code example

WP REST API V2 Auth

WP REST API Upload Image Media

Wordpress WP REST API V2 tutorial and code example upload image / media with PHP cURL

WP REST API V2 Auth

WP REST API jQuery Ajax Basic Authentication

WP REST API Basic Authentication With Jquery Ajax Tutorial and Code Example

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 Auth

WP REST API Create Post with jQuery Ajax

Wordpress WP REST API v2 tutorial create post with jquery ajax using basic authentication with code example