Using python and WordPress XML-RPC - Quick Reference

This article contains references about using python, and WordPress.

You need to install the package python-wordpress-xmlrpc to push data using the Python script to a WordPress post.

First, install the package on a Python machine (windows here) ( I am installing it on the virtual environment) using the pip command


cmd> pip install python-wordpress-xmlrpc

Second, check if XML-RPC is enabled by checking the below URL


https://your-wordpress-sitename/xmlrpc.php

and if you get an error like 403 forbidden or 404 not found check your .htaccess file if it is disabled or check the security plugins like wordfence if it is disabled from there.

You can enable it by adding the below lines in .htaccess file


<Files xmlrpc.php>
order deny,allow
allow from all
</Files>

Remember if it is not recommended to enable xml-rpc.

Third, if you get the error XML-RPC Server Accepts Post Requests Only, you can only do the post using the python XML-RPC package and it may be protected by the hosting company to protect against brute force attempts.

New Post

Here is an example of posting a new post on WordPress using python script


#new post

from wordpress_xmlrpc import Client, WordPressPost
from wordpress_xmlrpc.methods.posts import GetPosts, NewPost
from wordpress_xmlrpc.methods.users import GetUserInfo

wp = Client('https://www.example.com/xmlrpc.php', 'user', 'password')
post = WordPressPost()
post.title = 'My new title'
post.content = 'This is the body of my new post.'
post.terms_names = {
  'post_tag': ['tag1', 'tag2'],
  'category': ['category1', 'category2']
}
wp.call(NewPost(post))
print(post.id)

# end new post

It will create a new post "My New Title", if category1 and category2 not found it will create new categories and same as with tags.

New Post with Yoast Fields