I’m using the WP REST API plugin V2 (http://wp-api.org/).
Can the API upload a featured image and generate the related meta data?
I know I can upload an image attachment (POST /wp-json/wp/v2/media) and then update the related article (PUT /wp-json/wp/v2/posts/ID) and make its “featured_image” key point to the attachment id.
But is this the right way to do this?
Is it possible to generate different (resized) versions of the featured image after upload, or does this require a custom endpoint?
As far as I can tell thats the way to go. WP API docs is “a bit” short on explaining all this. And quite some frustration was involved but in the end thats exactly how I got it working.
So first upload the media to endpoint
POST /wp-json/wp/v2/media
, with the following HTTP headers and the file contents as data:The catch here was the Content-Disposition header.
This call should return the media ID, which you will need now for calling
POST /wp-json/wp/v2/posts/{$existingPostId}
.Same headers but without the
Content-Disposition
.This time the data should be JSON encoded
{"featured_media": 156}
(you dont have to use CURL directly. Just be sure to pass in the HTTP headers into the request)
To do this in one step, you can add a filter in PHP like this:
So, your call can pass a parameter for post ID to attach the media. Something like this:
File uploading worked in my side through following method:
I was able to create a post with an image id from uploading an image (ionic mobile).
I found the secret sauce by examining the the json response from wp-json/wp/v2/posts/id
In the data section I saw “featured_media”, I had read that I needed to set “featured_image” to an id but that didn’t work.
So I tried setting the “featured_media” value in my post and it works.
I tried everything, nothing worked until I tried this.
The “post_meta” array had no effect whatsoever, but I left it in there because that’s what they said to do in the (sparse) documentation I could find.
Here’s what worked for me: