Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WP REST API How to upload featured image?

Tags:

rest

wordpress

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?

like image 797
user2297996 Avatar asked Dec 18 '22 23:12

user2297996


2 Answers

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?

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:

            'CURLOPT_HTTPHEADER' => [
            'Content-type: application/json',
            'Authorization: Basic ' . $base64Credentials,
            'Content-Disposition: attachment; filename="acme.png"'
            ]

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)

like image 123
pHiL Avatar answered Dec 21 '22 13:12

pHiL


To do this in one step, you can add a filter in PHP like this:

add_filter('rest_prepare_attachment', 'attach_media_to_post',10,3); 
function attach_media_to_post($response, $post, $request) {
    if($request->get_method()!='POST'){
        return $response;
    }       
    $parameters = $request->get_params();       
    if(isset($parameters['featured'])){
        set_post_thumbnail($parameters['featured'],$post->ID);
    }
    return $response;
}

So, your call can pass a parameter for post ID to attach the media. Something like this:

http://yoursite.com/wp-json/wp/v2/media?featured=1234
like image 35
Rodrigo Souza Avatar answered Dec 21 '22 12:12

Rodrigo Souza