About this plugin
Note: You probably do not need this plugin. _embed to your URL and the response will then include all “embedded media”, including the featured image, and the data you get there is exactly what this plugin gives you. _embed.
_embed a try before using this plugin. 🙂
Version 2 of the WordPress REST API returns a featured_media field (formerly featured_image) on the post object by default, but this field is simply the image ID.
This plugin adds a better_featured_image field to the post object that contains the available image sizes and urls, allowing you to get this information without making a second request.
It takes this:
"featured_media": 13,
And turns it into this:
jpg" },
_embed. When no featured image has been set on the post the better_featured_image field will have a value of null.
I’ve done some basic performance tests that indicate the difference in response times with and without this plugin to be about 10-15ms for a collection of 10 posts and 0-5ms for a single post. For me this is much faster than making a second request to /media/, especially for multiple posts.
0, there is a filter better_rest_api_featured_image that allows you to add custom data to the better_featured_image field. The filter is directly on the return value of the function that returns the better_featured_image field. This can be used to do things like add custom image meta or an SVG version of the image to the response.
Here’s an example of how you might use it:
add_filter( 'better_rest_api_featured_image', 'xxx_modify_rest_api_featured_image', 10, 2 ); /** * Modify the Better REST API Featured Image response. * * @param array $featured_image The array of image data. * @param int $image_id The image ID.
* * @return array The modified image data. */ function xxx_modify_rest_api_featured_image( $featured_image, $image_id ) {
// Add an extra_data_string field with a string value. ';
// Add an extra_data_array field with an array value. ', );
return $featured_image; }
This plugin is on on Github and pull requests are always welcome. 🙂