Get in touch
Back to blog
September 27th, 2022

How To Get A Featured Image Using The WordPress API 

by Luca Reale
cropped-luca.png

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.

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.

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.

Locate the functions.php file in your WordPress dashboard by clicking on Tools then Theme File Editor

 Once your php file is open, add the following lines of code:

Code to add to functions.php to get the featured image with the WordPress API
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:

An example of adding the query parameter at the end of a URL to fetch a featured image with the WordPress API

The response will show you where your featured image is located.

The response from an API call for featured image using the query parameter

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:

Category:
cropped-luca.png
Luca Reale
Content writer

Our newsletter

Our links

Our Work

Our Content

Social

Copyright © 2024 Drewl (Luna Digital Ltd.). All rights reserved