Reading time: 2 minutes
Today we are going to learn how we can auto-publish posts on our WordPress using Python.
The first thing we need to do is create our remote_publish.py file.
def post_publisher(wpBaseURL, postStatus): WP_url = wpBaseURL + "/wp-json/wp/v2/posts" auth = HTTPBasicAuth(WORDPRESS_USERNAME, WORDPRESS_PASSWORD) headers = { "Accept": "application/json", "Content-Type": "application/json" } payload = json.dumps({ "status": postStatus, "title": "title", "content": "Content" }) response = requests.request( "POST", WP_url, data=payload, headers=headers, auth=auth ) print(response) post_publisher(BASE_URL_WORDPRESS, "publish")
First, we create the post_creator function, which allows us to create and send a post.
In the line: auth = HTTPBasicAuth(WORDPRESS_USERNAME, WORDPRESS_PASSWORD)
We need to specify our WordPress administrator’s Username and Password.
To generate one, use this URL:
https://URL_WORDPRESS/wp-admin/authorize-application.php
And generate a new key for the user you are using.
It will generate the password that you have to use.
The username is available in your profile.
Then we create the object to be sent, filling in the title and content.
And finally, it is sent.
To invoke the function, use this line: post_publisher(BASE_URL_WORDPRESS, "publish")
First, we need to indicate the base URL of our WordPress and the post status, in this case, publish.
If you need more information about what can be done with the WordPress API, you can use this URL: