Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save phamngsinh/964a7b3a828e17272babdcc2d5f6a38b to your computer and use it in GitHub Desktop.

Select an option

Save phamngsinh/964a7b3a828e17272babdcc2d5f6a38b to your computer and use it in GitHub Desktop.
WordPress API v2 image upload from media endpoint with Guzzle
/*
* WP REST API version 2.0-beta7
* API base url ishttp://www.example.com/wp-json
*
* Reference
* https://developer.wordpress.org/rest-api/reference/media/
*
* Description
* an example of loading image to WordPress API using Guzzle
* inspired by s-hiroshi's gist at https://gist.github.com/s-hiroshi/3477e07454d809b9d38f
* but here image data is sent in POST request body instead of multipart POST request
*/
/*
* Get Guzzle HTTP Client. That client has been authenticated.
*/
$client = ...
/*
* Get binary data of image.
* $path is file path to be uploaded.
*/
$fdata = file_get_contents($path);
// Get short filename
$filename = basename($path);
$headers = [
"Content-Disposition" => "form-data; filename=$filename",
'Content-Type' => mime_content_type($path),
];
/*
* Post media.
* Request to WP REST API media endpoint
*/
$response = $client->request(
'POST', 'wp-json/wp/v2/media', [
'headers' => $headers,
'body' => $fdata,
]
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment