How to add image and featured image to post by WP REST API

Question

my problem it is that I can’t see the images on media when I trigger this code from a Laravel application.

$newPost = $postClient->request('POST', 'http://www.localhost.com/wp-json/wp/v2/posts', [
            'headers' => [
                'Authorization' => 'Basic ' . base64_encode( $user . ':' . $password ),
            ],
            'verify' => false,
            'timeout'  => 2.0,
            'json' => [
                'title' => 'New title', 
                'excerpt' => 'testttt', 
                'content' => 'daaaaa',
                'status' => 'publish'
            ]
        ]);

        $newPostBody = json_decode($newPost->getBody());

        $fdata = file_get_contents('https://www.base64-image.de/build/img/mr-base64-482fa1f767.png');
        $media = $postClient->request('POST', 'http://www.localhost.com/wp-json/wp/v2/media', [
            'headers' => [
                'Authorization' => 'Basic ' . base64_encode( $user . ':' . $password ),
                'Content-Type' => 'image/jpg',
                'Accept' => 'images',
                'Cache-Control' => 'no-cache',
                'Content-Disposition' => 'form-data; name='.$data['title'].'; filename='.$data['title']
            ],
            'multipart' => [
                [
                    'name'     => 'imagineeeee',
                    'contents' => $fdata,
                    'filename' => $data['title'],
                ],
            ],
            'query' => [
                'status' => 'publish',
                'title' => 'File Title!',
                'comment_status' => 'open',
                'ping_status' => 'closed',
                'alt_text' => 'File Alt Text',
                'caption' => 'File Caption',
                'description' => 'File Description',
                'media_type' => 'image',
                'post' => $newPostBody->id
            ],
        ]);
        $media = json_decode($media->getBody());

The question is, how can I send image from an external link to a wordpress website by wp API and if the method it’s ok.
I need a post request to create the post(this is working ok) and after that I send the image on media. It’s any step that I need to do after that?
In media area I see a blank image only with the right size but I think that the encoded image that I sent it’s not ok.
Thank you!

0
Raz92 2 years 2019-11-22T03:12:00-05:00 0 Answers 52 views 0

Leave an answer

Browse
Browse