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(
'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 ),
),
'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:
- “Sorry, you are not allowed to upload this file type.” (Response code 500). It means that you didn’t provide the file inside the request. In the example above we get the file by URL with
file_get_contents()
function and then we pass this whole thing into thebody
of the request. Yes, in the official REST API documentation it is mentioned that you can pass image title, caption etc but it didn’t work out for me, so it seems like if you would like to add media title you have to do a second API request. Please don’t add anything inwp-config.php
to fix this error message. - “No Content-Disposition supplied.” (Response code 400). It is simple, you just have to pass a Content-Disposition header in format
attachment; filename="image.jpg"
.
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.


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
great help Misha, thanks!
you’re always welcome, Casey!