Posting to a wordpress blog from Python

If you are running a corporate website or a personal blog in WordPress, you may want to upload and update posts programmatically instead of from a browser. For this purpose, you can use python-wordpress-xmlrpc library.

github

  • The file in jupyter notebook format on github is here .

google colaboratory

  • If you want to run it on google colaboratory here 006/006_nb.ipynb)

Author’s environment

sw_vers
ProductName: Mac OS X
ProductName: Mac OS X
ProductVersion: 10.14.6
BuildVersion: 18G95
Python -V
Python 3.5.5 :: Anaconda, Inc.

Install python-wordpress-xmlrpc

! pip install python-wordpress-xmlrpc

Post an article

from wordpress_xmlrpc import Client, WordPressPost
from wordpress_xmlrpc.methods.posts import NewPost

wpSiteXMLRPC = 'https://xxxxxx.com/xmlrpc.php'
loginId = 'xxxx'
password = 'yyyy'

wp = Client(wpSiteXMLRPC, loginId, password)
post = WordPressPost()

title = 'title'
body = 'body body '

post.title = title
post.content = body

post.terms_names = {
  'post_tag': ['tag'],
  'category': ['category'], ['category']
}

# post.post_status = 'draft'
post.post_status = 'publish'

# set timezone to JST
post.date = datetime.datetime.now() - datetime.timedelta(hours=9)

# custom field
customFields = [].
customFields.append({
  'key': 'aaa',
  'value': '***'
})

post.custom_fields = customFields

new_id = int(wp.call(NewPost(post)))
if new_id > 0:
  print('wordpress update success.')
else:
  print('wordpress update failure.')

Uploading images

To upload an article with images, first upload the article itself, get its ID (media ID), and then specify the ID when you upload the article. The sample code to upload an image is as follows

from wordpress_xmlrpc import Client, WordPressPost
from wordpress_xmlrpc.methods import media

wpSiteXMLRPC = 'https://xxxxxx.com/xmlrpc.php'
loginId = 'xxxx'
password = 'yyyy'

wp = Client(wpSiteXMLRPC, loginId, password)
post = WordPressPost()

def upload_image(in_image_file_name, out_image_file_name):
  if os.path.exists(in_image_file_name):
    with open(in_image_file_name, 'rb') as f:
      binary = f.read()

    data = {
      "name": out_image_file_name,
      "type": 'image/jpeg',
      "overwrite": True,
      "bits": binary
    }

    media_id = wp.call(media.UploadFile(data))['id'].
    print(in_image_file_name.split('/')[-1], 'upload success')
    return
  else:
    print(in_image_file_name.split('/')[-1], 'NO IMAGE!!!')

Specify thumbnails.

You can specify a thumbnail for a post by uploading an image and setting it to post.thumbbail as shown below.

post = WordPressPost()
media_id = wp.call(media.UploadFile(data))['id'].
post.thumbnail = media_id

You can post an article, get a list of articles even if you don’t update them, upload a fixed page, and update it. For more information, check out the python-wordpress-xmlrpc site .