Created
January 12, 2018 10:27
-
-
Save lebedevsergey/43132d26e21c5be3092da4acab9060a6 to your computer and use it in GitHub Desktop.
WordPress API v2 image upload from media endpoint with Guzzle
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /* | |
| * 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