Created
November 24, 2015 21:31
-
-
Save s-hiroshi/3477e07454d809b9d38f to your computer and use it in GitHub Desktop.
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://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), | |
], | |
], | |
); |
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 ?
@jeffochoa also check this, which took me a while to figure out. https://gist.github.com/jamiechong/ed2b569fb879015f66c33eb2cbe6576d
$id = json_decode($response->getBody()->getContents())->id;
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',
],
]);
It finally worked... wow. Thank you so much!
For anyone looking for a python script with media property support:
from requests_toolbelt.multipart.encoder import MultipartEncoder
import requests
import os
def upload_img_wp(imgPath):
fileName = os.path.basename(imgPath)
multipart_data = MultipartEncoder(
fields={
# a file upload field
'file': (fileName, open(imgPath, 'rb'), 'image/jpg'),
# plain text fields
'alt_text': 'alt test',
'caption': 'caption test',
'description': 'description test'
}
)
res = requests.post('http://example.com/wp-json/wp/v2/media', data=multipart_data,
headers={'Content-Type': multipart_data.content_type},
auth=('user', 'pass'))
id = 0
link = ''
if res.status_code == 201:
id = res.json()['id']
link = res.json()['guid']["rendered"]
#id may be used to set 'featured_media' field of created post
else:
print("Unexpected status code: {}".format(response.status_code))
return id, link
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Dude!!! I spend like 4 hours looking for this! Thanks 👍