Skip to content

Instantly share code, notes, and snippets.

@oshri-humanz
Created May 27, 2020 17:58
Show Gist options
  • Save oshri-humanz/ecd7a93711c0e5078d5849bd2a6adcd2 to your computer and use it in GitHub Desktop.
Save oshri-humanz/ecd7a93711c0e5078d5849bd2a6adcd2 to your computer and use it in GitHub Desktop.
Wordpress REST API create new post with image/media attachment (upload) using python
import requests
import json
import base64
import os
import mimetypes
#### defs ####
user = os.environ.get("WORDPRESS_API_USER", "")
pythonapp = os.environ.get("WORDPRESS_API_KEY", "")
url = os.environ.get("WORDPRESS_API_ENDPOINT", "")
data_string = user + ':' + pythonapp
token = base64.b64encode(data_string.encode())
### Upload wordpress media, return id or None
def uploadMedia(media_path):
try:
headers = {'Authorization': 'Basic ' + token.decode('utf-8'), "Content-Type": mimetypes.guess_type(media_path)[0], 'Content-Disposition': 'attachment; filename=%s' % os.path.basename(media_path)}
res = requests.post(url + '/media', headers=headers, data=open(media_path, 'rb').read())
newDict = res.json()
newID = newDict.get('id')
print ('created new media %s' % newID)
return newID
except Exception as e:
print(e)
return None
### Create wordpress post, return link or None
def createPost(post):
try:
headers = {'Authorization': 'Basic ' + token.decode('utf-8')}
r = requests.post(url + '/posts',headers=headers, json=post)
return json.loads(r.content.decode('utf-8'))['link']
except Exception as e:
print(e)
return None
### TEST -> create featured image on wordpress and post
media = uploadMedia('../static/images/logo.png')
print createPost({'date': '2020-05-19T20:00:35',
'title': 'First REST API post',
'slug': 'rest-api-1',
'status': 'publish',
'content': 'this is the content post',
'author': '1',
'excerpt': 'Exceptional post!',
'format': 'standard',
'featured_media': media })
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment