When making an API call for a WordPress post, you’ve probably found it frustrating that the response object doesn’t return the URL for the featured image. Fortunately, there are some quick workarounds to get a featured image using the WordPress REST API.
In this article, we’ll explain three methods of using the WordPress API to get a featured image.
Method 1: Better REST API Featured Images Plugin
This plugin extends the REST API posts endpoint and adds the featured image URLs in the response. Additionally, it provides different image sizes and the respective URLs for them.
Method 2: Add a Featured Image Directly to the API
The second method of using the WordPress API to get a featured image involves editing the functions.php file.
In your WordPress dashboard, navigate to Tools>Theme File Editor. You’ll find the functions.php file on the right-hand side.
Once your php file is open, add the following lines of code:
add_action('rest_api_init', 'register_rest_images' );function register_rest_images(){
register_rest_field( array('post'),
'fimg_url',
array(
'get_callback' => 'get_rest_featured_image',
'update_callback' => null,
'schema' => null,
)
);
}function get_rest_featured_image( $object, $field_name, $request ) {
if( $object['featured_media'] ){
$img = wp_get_attachment_image_src( $object['featured_media'], 'app-thumb' );
return $img[0];
}
return false;
}
Save your file by clicking on Update File at the bottom of the window and then you’re all done!
Method 3: Using the Query Parameter
This method lets you fetch the URL of your featured image using the query parameter ?_embed. You simply add ?_embed at the end of the URL like this:
The response will show you where your featured image is located.
Get Your Featured Images with the WordPress API
With these three methods, you can easily fetch featured images for your post with the REST API. Luckily, it’s pretty straightforward, just remember to be careful when editing the functions.php file and make a backup before changing any site files.
If you’re not confident about changing the functions.php file, you can install and use the Better REST API Featured Images plugin or the ?_embed query parameter to get your featured images.
More WordPress tips & tricks for you…
If you found this helpful, you might like to check out some of our other WordPress guides like: