WP Rest API: details of latest post including featured media url in one request?

Ah I just had this problem myself! And while _embed is great, in my experience it is very slow, and the point of JSON is to be fast 😀

I have the following code in a plugin (used for adding custom post types), but I imagine you could put it in your theme’s function.php file.

php

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];
}

Now in your JSON response you should see a new field called "featured_image_src": containing a url to the thumbnail.

Read more about modifying responses here:
http://v2.wp-api.org/extending/modifying/

And here’s more information on theregister_rest_field and wp_get_attachment_image_src() functions:
1.) https://developer.wordpress.org/reference/functions/register_rest_field/
2.) https://developer.wordpress.org/reference/functions/wp_get_attachment_image_src/

**Note: Don’t forget <?php ?> tags if this is a new php file!

Leave a Comment

error code: 523