How to use Python to write a post in your WordPress website/blog

Wordpress/Python integration

Why does it matter? Because we might need to write several posts with relatively similar content at the same time.

First of all, I need to install a Python library to interact with the WordPress blog. We can install it easily by the following code in command prompt. Open CMD.exe in your windows machine, and run:

pip install python-wordpress-xmlrp

This command will add python-wordpress-xmlrpc library to your installed Python. This library interacts using WordPress XML-RPC API. It is very easy to work with this library. I need to first import the required classes as:

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

Then I need to declare my WordPress blog login information:

your_blog = Client('http://MYWEBSITE.com/xmlrpc.php', 'USERNAME', 'PASSWORD')

Then, I can access to the posts by the following line:

myposts=your_blog.call(posts.GetPosts())

Now, I want to write a new post and publish it in my WordPress blog:

post = WordPressPost()
post.title = 'MY_POST_TITLE'
post.slug='MY_POST_PERMANENT_LINK'
post.content = 'YOUR_POST_CONTENT'
post.id = your_blog.call(posts.NewPost(post))
post.post_status = 'publish'
your_blog.call(posts.EditPost(post.id, post))

In line 2, I can choose the title of the post. In line 3, I can choose the URL of the post. For example, I can choose “how-to-use-python-to-write-a-post-in-your-wordpress-website“. In line 4, I can write my post content. New lines, new tabs, and etc. can be used according to Python syntax. In line 6, you set the status of the post as “publish”ed!

and, the post is automatically uploaded in the WordPress blog.

More information on this Python library : python-wordpress-xmlrpc

2 comments

Leave a Reply