Search
Close this search box.

WordPress: How to get featured media url in rest api?

Amitpal Singh
Amitpal Singh
February 11, 2022
WP Rest API: details of latest post including featured media url in one request?

WP Rest API – How to get featured image?

add_action( 'rest_api_init', 'add_thumbnail_to_JSON' );
function add_thumbnail_to_JSON() {
//Add featured image
register_rest_field( 
    'post', // Where to add the field (Here, blog posts. Could be an array)
    'featured_image_src', // Name of new field (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'], // Image attachment ID
    'thumbnail',  // Size.  Ex. "thumbnail", "large", "full", etc..
    true // Whether the image should be treated as an icon.
  );
  return $feat_img_array[0];
} 

Share this post:

How to Attribute?

Lorem ipsum is typically a corrupted version of De finibus bonorum et malorum, a 1st-century BC text by the Roman statesman and philosopher Cicero.
for Example: Website, Social Media, Blogs, ebooks , newsletter, etc.
Lorem ipsum is typically a corrupted version of De finibus bonorum et malorum, a 1st-century BC text by the Roman statesman and philosopher Cicero.
Copied!

Got a Question? Check out our FAQ Section.

Your action, our appreciation

It encourage us to give you more valuable content on website.