Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
/*
* WP REST API version 2.0-beta7
* API base url ishttp://www.example.com/wp-json
*
* Reference
* https://wordpress.org/support/topic/new-post-with-image
*/
/*
* Get Guzzle HTTP Client. That client has been authenticated.
*/
$client = ...
/*
* Get binary data of image.
* $path is file path to be uploaded.
*/
$handle = fopen($path, 'r');
$fdata = fread($handle, filesize($path));
/*
* Post media.
* Request to WP REST API media endpoint
*/
$response = $client->request(
'POST',
'wp/v2/media',
[
'multipart' => [
[
'name' => 'file',
'contents' => $fdata,
'filename' => basename($path),
],
],
);
@jeffochoa

This comment has been minimized.

Copy link

@jeffochoa jeffochoa commented Jul 3, 2017

Dude!!! I spend like 4 hours looking for this! Thanks 👍

@jeffochoa

This comment has been minimized.

Copy link

@jeffochoa jeffochoa commented Jul 3, 2017

Hmm.. odd... for some reason I get "null" response for this request. The image is being stored in wordpress but. How can I get the id ?

@jamiechong

This comment has been minimized.

Copy link

@jamiechong jamiechong commented Jul 20, 2017

@jeffochoa also check this, which took me a while to figure out. https://gist.github.com/jamiechong/ed2b569fb879015f66c33eb2cbe6576d

@rehmatworks

This comment has been minimized.

Copy link

@rehmatworks rehmatworks commented Oct 10, 2017

@jeffochoa

 $id = json_decode($response->getBody()->getContents())->id;
@ahmeti

This comment has been minimized.

Copy link

@ahmeti ahmeti commented Nov 2, 2018

You can use query array If you want send media properties!

$response = $client->request(
    'POST',
    'wp/v2/media', 
    [
        'multipart' => [
            [
                'name'     => 'file',
                'contents' => $fdata,
                'filename' => basename($path),
            ],
        ],
        
        'query' => [
            'status' => 'publish',
            'title' => 'File Title!',
            'comment_status' => 'open',
            'ping_status' => 'closed',
            'alt_text' => 'File Alt Text',
            'caption' => 'File Caption',
            'description' => 'File Description',
        ],
    ]);
@kevnk

This comment has been minimized.

Copy link

@kevnk kevnk commented Aug 2, 2019

It finally worked... wow. Thank you so much!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment