Programmatically Create A Post With Custom Fields In WordPress

This post expands on what I discuss in the post Use Python & WP’s REST API To Create a Post On WordPress. For that script, I demonstrated how to automate creating new content on WordPress using WP’s REST API and the Python-WordPress-XMLRPC library.

What I didn’t cover is how to create posts that have custom fields. WordPress allows users to create their own fields when creating content, and plugins frequently add their own fields as well.

The script I published in August 2017 can be easily tweaked to automatically add a custom field to a new post. Note new lines 15 and 16 in the script below. These two lines add a custom field called ‘operating_system’ to the post. The field has a value of ‘ubuntu1604’.

You will need to install the Python-WordPress-XMLRPC library and you may need to enable RPC posting. My previous post covers both topics.

from wordpress_xmlrpc import WordPressPost
from wordpress_xmlrpc import Client
from wordpress_xmlrpc.methods import posts
from wordpress_xmlrpc.methods.posts import NewPost
 
#For security, consider creating a user just for your script.
username = 'wordpress_username_here'
password = 'wordpress_password_here'
wp = Client('http://sandbox.nextfridayit.com/xmlrpc.php', username, password)
post = WordPressPost()
 
post.title = 'Automating WordPress'
post.content = 'This is the body of my new post.\n\n Here is a new line. <strong>HTML works fine!</strong>'
post.post_status = 'publish'
post.custom_fields = []
post.custom_fields.append({'key':'operating_system','value':'ubuntu1604'})
 
wp.call(NewPost(post))