Python

How to auto post in WordPress using Python

In this article, introduce how to auto post in WordPress using Python.

Let’s get straight to the point.

My development project’s code

The following code is my development project’s code.

It’s actually used now.

import os
from wordpress_xmlrpc import Client, WordPressPost
from wordpress_xmlrpc.methods.posts import NewPost, GetPost, EditPost
from wordpress_xmlrpc.methods.media import UploadFile

class WordPressAuto:

    def __init__(self, id, password, url, which=None):
        # WordPress admin credentials
        self.id = id
        self.password = password
        # URL for logging into WordPress (accessible by third parties)
        self.url = url

        # Determine whether to save as draft or publish
        #self.which="publish"
        self.which="draft"

        # Initialize WordPress client
        self.wp = Client(self.url, self.id, self.password)

    def wp_upload_image(self, img_path, out_img_name=None, overwrite=True):
        # If no output image name is specified, use the filename
        if out_img_name is None:
            out_img_name = os.path.basename(img_path)

        # Check if the image file exists
        if os.path.exists(img_path):
            with open(img_path, 'rb') as f:
                binary = f.read()

            data = {
                "name": out_img_name,  # File name
                "type": 'image/jpeg',  # MIME type (can be adjusted based on image format)
                "overwrite": overwrite,  # Whether to overwrite existing files
                "bits": binary  # Image binary data
            }

            # Upload image and retrieve media ID
            response = self.wp.call(UploadFile(data))
            media_id = response['id']
            print(f"WordPress: Successfully uploaded {out_img_name}. ID: {media_id}")
            return media_id
        else:
            print(f"WordPress: {out_img_name} not found")
            return None

    def wp_auto_post(self, title, content, category, img_path=None):
        # Create a new WordPress post
        post = WordPressPost()
        post.post_status = self.which  # Set post status (draft or publish)
        post.title = title  # Set post title
        post.content = content  # Set post content
        post.terms_names = {
            "category": category  # Set post category
        }

        # Upload an image and set thumbnail if image path is provided
        if img_path:
            media_id = self.wp_upload_image(img_path)
            if media_id:
                post.thumbnail = media_id  # Assign thumbnail image to post

        return self.wp.call(NewPost(post))  # Publish the post

How to use python package

If you want to post article by auto, You can use python package’s “wordpress-xmlrpc”.

1. Install “wordpress-xmlrpc”

First, You need to install “wordpress-xmlrpc” in your computer.

pip install python-wordpress-xmlrpc

2. Prepare python code

You need to prepare python code.

But you don’t need to write new code.

You can use the following code.

import os
from wordpress_xmlrpc import Client, WordPressPost
from wordpress_xmlrpc.methods.posts import NewPost, GetPost, EditPost
from wordpress_xmlrpc.methods.media import UploadFile

class WordPressAuto:

    def __init__(self, id, password, url, which=None):
        # WordPress admin credentials
        self.id = id
        self.password = password
        # URL for logging into WordPress (accessible by third parties)
        self.url = url

        # Determine whether to save as draft or publish
        #self.which="publish"
        self.which="draft"

        # Initialize WordPress client
        self.wp = Client(self.url, self.id, self.password)

    def wp_upload_image(self, img_path, out_img_name=None, overwrite=True):
        # If no output image name is specified, use the filename
        if out_img_name is None:
            out_img_name = os.path.basename(img_path)

        # Check if the image file exists
        if os.path.exists(img_path):
            with open(img_path, 'rb') as f:
                binary = f.read()

            data = {
                "name": out_img_name,  # File name
                "type": 'image/jpeg',  # MIME type (can be adjusted based on image format)
                "overwrite": overwrite,  # Whether to overwrite existing files
                "bits": binary  # Image binary data
            }

            # Upload image and retrieve media ID
            response = self.wp.call(UploadFile(data))
            media_id = response['id']
            print(f"WordPress: Successfully uploaded {out_img_name}. ID: {media_id}")
            return media_id
        else:
            print(f"WordPress: {out_img_name} not found")
            return None

    def wp_auto_post(self, title, content, category, img_path=None):
        # Create a new WordPress post
        post = WordPressPost()
        post.post_status = self.which  # Set post status (draft or publish)
        post.title = title  # Set post title
        post.content = content  # Set post content
        post.terms_names = {
            "category": category  # Set post category
        }

        # Upload an image and set thumbnail if image path is provided
        if img_path:
            media_id = self.wp_upload_image(img_path)
            if media_id:
                post.thumbnail = media_id  # Assign thumbnail image to post

        return self.wp.call(NewPost(post))  # Publish the post

# Post on WordPress
wp_id = "Your wordpress login id"
wp_password= "Your wordpress login password"
wp_url= "https://your_domain.com/xmlrpc.php"
wp = WordPressAuto(wp_id, wp_password, wp_url)
generated_image = True # parameter of generate image
title = "test title"
content = "test content"
category_list = ["test"] # if there are more than two categories, add new category in array
img_path = "image_path"
try:
    print(f"Post article - execute datetime: {datetime.now()} - article title: {title}")
    if generated_image:
        wp_post_id = wp.wp_auto_post(title=title, content=content, category=category_list, img_path=img_path)
    else:
        wp_post_id = wp.wp_auto_post(title=title, content=content, category=category_list)
    wp_post_url = wp.get_wp_post_link(wp_post_id)
    print(f"Completed article posting - execute datetime: {datetime.now()} - article title: {title}")
except Exception as e:
    print(f"Failed article posting - execute datetime: {datetime.now()} - error log: {e}")

3. Execute python file

Save the above code in your computer.

Any file name is fine.

For example, when you downloaded file name as “wp_auto_post.py”, you need the following command in

python wp_auto_post.py

If output like the following log in your computer, success posting.

But, you should check on your WordPress site whether it post.

Completed article posting – execute datetime: 2025-06-20 02:32:15.123456
– article title: test title

If out put error log, you check error log.

And then check the file(name, code, etc..) or your computer or WordPress setting(login id, password, server setting).