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 Post By Id With PHP

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

wp rest api v2

Disable WP Rest API V2

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

wp rest api v2

WP REST API Create Category PHP cURL

Wordpress Tutorial WP REST API V2 Create Category With PHP cURL with code example

WP REST API V2 Auth

Autocomplete WordPress Search Form With WP REST API

WordPress Tutorial Create Autocomplete Search Form Using WP REST API V2 With Code Example

WP REST API V2 Auth

WP REST API Create User With PHP cURL

WP REST API Create User With PHP cURL. PHP code example to create user for your wordpress website.