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. Or not exactly a featured image, it works the same when you want to upload any image with REST API.

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(
	'https://WEBSITE-DOMAIN/wp-json/wp/v2/media',
	array(
		'headers' => array(
			'Authorization' => 'Basic ' . base64_encode( "$login:$password" ),
			'Content-Disposition' => 'attachment; filename="' . basename( $url ) . '"',
			'Content-Type' => wp_get_image_mime( $url ), // or mime_content_type()
		),
		'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:

Updating image information (alt, title, caption text)

Well, to upload an image with API is one thing, but in order to provide some of its information, you will need to send an additional REST API request. I mean these fields:

WordPress REST API featured image alt text and caption update

Let’s try an example now – just to update an image alt text. So we need to send a POST request to this enpoint /wp/v2/media/<id>.

wp_remote_post(
		'https://WEBSITE-DOMAIN/wp-json/wp/v2/media/' . $featured_image_id,
		array(
			'headers' => array(
				'Authorization' => 'Basic ' . base64_encode( "$login:$password" )
			),
			'body' => array(
				'alt_text' => 'looks like mountain',
				//'caption'  => '',
				//'description' => '',
				//'title' => '',
			)
		)
);

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.

wp_remote_post(
		'https://WEBSITE-DOMAIN/wp-json/wp/v2/posts',
		array(
			'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 X