Get Post with Featured Image URL in REST API
I noticed that when people read my post about uploading a featured image via WordPress REST API, they are also searching how to get a post with its featured image URL.
So I decided to say a couple words about it.
First of all I would like to mention that when you get a post using WordPress REST API featured image ID is already included there.
$request = wp_remote_get( "https://YOU-SITE/wp-json/wp/v2/posts/$post_id" );
if( 'OK' === wp_remote_retrieve_response_message( $request ) ) {
$body = json_decode( wp_remote_retrieve_body( $request ), true );
echo $body[ 'featured_image' ];
}
But the thing is that sometimes we need to get a featured image URL as well, at least we wouldn’t need to perform additional REST API requests to /wp/v2/media/$image_id
.
The good new is that it is quite easy to do, we can just register one more field in REST API response with a simple filter hook and register_rest_field()
function.
add_action( 'rest_api_init', function() {
register_rest_field(
'post', // an object type (like "post", "term", "comment")
'featured_image_data', // we are going to store image information here
array(
'get_callback' => 'rudr_get_featured_image_data',
)
);
} );
function rudr_get_featured_image_data( $post, $field_name, $request ) {
if( empty( $post[ 'featured_media' ] ) ) {
return;
}
$image_id = (int) $post[ 'featured_media' ];
if( ! $image = get_post( $image_id ) ) {
return;
}
return array(
'src' => wp_get_attachment_url( $image_id ),
'alt' => get_post_meta( $image_id, '_wp_attachment_image_alt', true ),
'caption' => $image->post_excerpt
);
}
Once you inserted the code above to the… I hope you know where. Then you can create REST API requests to that website and featured get image URLs of its post. Let’s slightly change the first example in this tutorial now:
echo "<img src='{$body[ 'featured_image_data' ][ 'src' ]}' alt='{$body[ 'featured_image_data' ][ 'alt' ]}' />";

Misha Rudrastyh
Hey guys and welcome to my website. For more than 10 years I've been doing my best to share with you some superb WordPress guides and tips for free.
Need some developer help? Contact me