Blog / WordPress/ Automate WordPress Post Publishing with Python and wordpress_xmlrpc

Automate WordPress Post Publishing with Python and wordpress_xmlrpc

使用 Python wordpress_xmlrpc 模块批量发布文章到 WordPress

Overview

The Python python-wordpress-xmlrpc library enables interaction with WordPress sites via the XML-RPC protocol, allowing for automated tasks like publishing posts, managing categories and tags, and uploading media files. This guide covers basic installation, usage, and code examples for common scenarios.

Installation

Install using pip:

pip install python-wordpress-xmlrpc

Basic Usage: Publishing a Post

First, import the necessary modules and establish a client connection.

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

# Establish connection
wp = Client('https://your-site.com/xmlrpc.php', 'username', 'password')

Note: Replace the URL, username, and password with your own WordPress site credentials. It is recommended to use an application password rather than your main administrator password.

Publishing a Basic Post

post = WordPressPost()
post.title = 'Post Title'
post.content = 'Post Content'
post.post_status = 'publish'  # Status: 'draft', 'publish', 'private'

# Set tags and categories
post.terms_names = {
    'post_tag': ['Tag1', 'Tag2'],
    'category': ['Category1', 'Category2']
}

# Publish and get the post ID
post_id = wp.call(posts.NewPost(post))
print(f"Post published, ID: {post_id}")

Publishing a Post with Custom Fields

Custom Fields allow you to store additional metadata for a post.

post = WordPressPost()
post.title = 'Post with Custom Fields'
post.content = 'Post body'
post.post_status = 'publish'

# Add custom fields
post.custom_fields = []
post.custom_fields.append({'key': 'price', 'value': 99.9})
post.custom_fields.append({'key': 'location', 'value': 'Beijing'})

post_id = wp.call(posts.NewPost(post))

Publishing a Post with a Featured Image

You must first upload the image as a media file to get its attachment ID, then set it as the post's thumbnail.

from wordpress_xmlrpc.methods import media
from wordpress_xmlrpc.compat import xmlrpc_client

# Upload image
filename = './featured-image.jpg'

with open(filename, 'rb') as img:
    data = {
        'name': 'featured-image.jpg',
        'type': 'image/jpeg',  # Adjust based on file type
        'bits': xmlrpc_client.Binary(img.read())
    }

response = wp.call(media.UploadFile(data))
attachment_id = response['id']  # Get uploaded image ID

# Create post and set featured image
post = WordPressPost()
post.title = 'Post with Featured Image'
post.content = 'Post body'
post.post_status = 'publish'
post.thumbnail = attachment_id  # Set featured image ID

post_id = wp.call(posts.NewPost(post))

Managing Categories and Tags

You can create categories and tags independently, not just when publishing a post.

Creating a New Tag

from wordpress_xmlrpc import WordPressTerm
from wordpress_xmlrpc.methods import taxonomies

tag = WordPressTerm()
tag.taxonomy = 'post_tag'
tag.name = 'New Tag'
tag.slug = 'new-tag-slug'  # Optional, URL-friendly name

tag_id = wp.call(taxonomies.NewTerm(tag))
print(f"Tag created, ID: {tag_id}")

Creating a New Category

cat = WordPressTerm()
cat.taxonomy = 'category'
cat.name = 'New Category'
cat.slug = 'new-category-slug'

cat_id = wp.call(taxonomies.NewTerm(cat))
print(f"Category created, ID: {cat_id}")

Creating a Child Category

# Assuming parent category ID is 10
parent_cat_id = 10

child_cat = WordPressTerm()
child_cat.taxonomy = 'category'
child_cat.parent = parent_cat_id
child_cat.name = 'Child Category'
child_cat.slug = 'child-category'

child_cat_id = wp.call(taxonomies.NewTerm(child_cat))
print(f"Child category created, ID: {child_cat_id}")

Notes and Best Practices

  • Security: Do not hard-code passwords in your script. Use environment variables or configuration files to manage sensitive information.
  • Error Handling: Add try-except blocks in production scripts to handle exceptions like network errors or authentication failures.
  • Batch Operations: When publishing in bulk, add appropriate delays in loops to avoid overloading the server.
  • Library Version: Examples are based on a recent version of python-wordpress-xmlrpc. Ensure you have the latest version installed.

Using these methods, you can flexibly automate the management of your WordPress content with Python scripts.

Post a Comment

Your email will not be published. Required fields are marked with *.