Skip to content

Instantly share code, notes, and snippets.

@openroomxyz
Last active April 29, 2024 15:18
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save openroomxyz/f32021d077d1be5235ceb1a716d1e37a to your computer and use it in GitHub Desktop.
Save openroomxyz/f32021d077d1be5235ceb1a716d1e37a to your computer and use it in GitHub Desktop.
Python WordPress API : How to upload image to wordpress?
import base64, requests, json
def header(user, password):
credentials = user + ':' + password
token = base64.b64encode(credentials.encode())
header_json = {'Authorization': 'Basic ' + token.decode('utf-8')}
return header_json
def upload_image_to_wordpress(file_path, url, header_json):
media = {'file': open(file_path,"rb"),'caption': 'My great demo picture'}
responce = requests.post(url + "wp-json/wp/v2/media", headers = header_json, files = media)
print(responce.text)
hed = header("admin","XXXX XXXX XXXX XXXX XXXX XXXX") #username, application password
upload_image_to_wordpress('C://Users//X//Desktop//X//X.png', 'https://XXX.xyz/XXX/',hed)
@tonyanhq
Copy link

Thank you so much!

@dragonsxslayer
Copy link

why importing json if you never used it ?

@Infinitusvoid
Copy link

why importing json if you never used it ?

It looks like it's not necesery, as it seems not used. Thanks!

@SujitX
Copy link

SujitX commented Dec 27, 2022

SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape

@vjvasiljev
Copy link

Thank you so much!

@warped-kings
Copy link

SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape

If you're on windows, you may need to add an 'r' in front of your file path or use double '\'
ex: file = r"C:\Users*user*\Desktop*image*" or file = "C:\Users\user\Desktop\image"

@mzakariabigdata
Copy link

How can I add title ?

@Gurke258
Copy link

Gurke258 commented Apr 29, 2024

Hello,

i get some Error:

<html>
<head><title>403 Forbidden</title></head>
<body>
<center><h1>403 Forbidden</h1></center>
<hr><center>nginx</center>
</body>
</html>

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