Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Upload Media to WordPress using REST API

how to upload media-image or featured-image in wordpress using rest api.

I've created new post using WordPress REST API, and now I am uploading Image to my Wordpress Site using REST API but i am unable to achieve it due to error "No data Supplied" kindly please Check Screenshot

enter image description here

which is the best way to create new post in WordPress with Featured Image, right now in my mind

  1. Upload Media File to WordPress Site and Get Media ID
  2. Create New Post with Media ID
like image 304
jkdobariya Avatar asked Jul 11 '26 01:07

jkdobariya


2 Answers

you almost right, just lack media(image) raw binary data.

for python, using code:

import requests

toUploadImagePath = "/xxx/xxx.jpg"
mediaImageBytes = open(toUploadImagePath, 'rb').read()
# b'\xff\xd8\xff\xe0\x00\x10JFIF\x00\x01\x01\.....'

uploadImageFilename = "661b943654f54bd4b2711264eb275e1b.jpg"
curHeaders = {
  "Authorization": "Bearer xxx.yyy.zzz-xxx-yyy-zzz",
  "Content-Type": "image/jpeg",
  "Accept": "application/json",
  'Content-Disposition': "attachment; filename=%s" % uploadImageFilename,
}

resp = requests.post(
  "https://www.crifan.com/wp-json/wp/v2/media",
  headers=curHeaders,
  data=mediaBytes,
)

full code can refer my lib: crifanWordpress.py

and my Chinese post: 【已解决】用Python通过WordPress的REST API上传图片 (will publish in short future)

like image 138
crifan Avatar answered Jul 13 '26 14:07

crifan


Using the REST API to upload a file to WordPress is quite simple. All you need is to send the file in a POST-Request to the wp/v2/media route.

UPDATED added data response true

$file = file_get_contents( 'test.jpg' );
$url = 'http://example.com/wp-json/wp/v2/media/';
$ch = curl_init();
$username = 'admin';
$password = 'password';

curl_setopt( $ch, CURLOPT_URL, $url );
curl_setopt( $ch, CURLOPT_POST, 1 );
curl_setopt( $ch, CURLOPT_POSTFIELDS, $file );
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt( $ch, CURLOPT_HTTPHEADER, [
    'Content-Disposition: form-data; filename="example.jpg"',
    'Authorization: Basic ' . base64_encode( $username . ':' . $password ),
] );
$result = curl_exec( $ch );
curl_close( $ch );
print_r( json_decode( $result ) );

MORE https://gist.github.com/ahmadawais/0ccb8a32ea795ffac4adfae84797c19a


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!