Upload Featured Image to a Post with REST API

Recently I have updated the tutorial about creating a post with WordPress REST API but I didn’t cover a topic of featured images there.

It is not that simple actually, but I will make it simple for you.

1. Upload an Image with REST API

$url = 'FILE URL';

$request = wp_remote_post(
		'headers' => array(
			'Authorization' => 'Basic ' . base64_encode( "$login:$password" ),
			'Content-Disposition' => 'attachment; filename="' . basename( $url ) . '"',
			'Content-Type: ' . wp_get_image_mime( $url ),
		'body' => file_get_contents( $url )

if( 'Created' === wp_remote_retrieve_response_message( $request ) ) {
	$body = json_decode( wp_remote_retrieve_body( $request ) );
	$featured_image_id = $body->id;

Great, now we have an uploaded image ID we are going to use it soon.

As you can see I am a fan of using default WordPress HTTP API functions, but of course feel free to use cURL or whatever you want.

Some errors you could face with:

2. Create a Post with Featured Image

As I said we’ve already covered post creation with REST API, so here is just a simple example of supplying a featured image ID into the request.

			'headers' => array(
				'Authorization' => 'Basic ' . base64_encode( "$login:$password" )
			'body' => array(
				'title'   => 'My test',
				'status'  => 'draft',
				'featured_media' => $featured_image_id,

That’s pretty much it.

upload featured image to a post with WordPress REST API
Misha Rudrastyh

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

Follow me on Twitter