How to Set the Category When Uploading a WordPress Post in Python?

5/5 - (2 votes)

When uploading a blog post on a WordPress blog in Python using /wp-json/wp/v2/posts, how do I set the category?

You can set the category for a post using the WordPress REST API by specifying the 'categories' field in your request body. This field should be a list of category IDs.

Here’s a simple Python example using the requests library:

import requests
import json

url = 'https://yourwebsite.com/wp-json/wp/v2/posts'
headers = {'Content-Type': 'application/json'}
auth = ('username', 'password')  # replace with your username and password

data = {
    'title': 'My New Post',
    'content': 'This is the content of my new post.',
    'status': 'publish',
    'categories': [4, 18]  # replace with your category IDs
}

response = requests.post(url, headers=headers, auth=auth, data=json.dumps(data))

print(response.status_code)
print(response.json())

This script will upload a new post to your blog with the title "My New Post", the content "This is the content of my new post.", and it will be immediately published under the categories with the IDs 4 and 18. You’ll want to replace these placeholders with your actual website URL, username, password, and category IDs.

Note that to use this method, you must have the correct authentication set up. The Basic Auth plugin can be used for testing purposes, but for a live site you’ll likely want to use a more secure method such as OAuth.

Personally, I use HTTPBasicAuth in Python like so:

Also, the category IDs can be obtained through another API endpoint (https://yourwebsite.com/wp-json/wp/v2/categories).

Make sure your account has the right permissions to create a post and also to assign categories, otherwise, you may get permission errors.

Where Can I Find the Existing Category IDs?

You can find the existing category IDs using the WordPress REST API’s /categories endpoint. The endpoint will return a list of category objects, and each object will have an id field which is the category ID.

Here’s a Python example of how to get the categories using the requests library:

import requests

url = 'https://yourwebsite.com/wp-json/wp/v2/categories'
response = requests.get(url)

if response.status_code == 200:
    categories = response.json()
    for category in categories:
        print('Category ID:', category['id'])
        print('Category Name:', category['name'])
        print('-----------------------------')
else:
    print('Failed to retrieve categories. Status code:', response.status_code)

Replace 'https://yourwebsite.com' with the URL for your website.

This script will print out the ID and name of each category.

How Do I Create a New Category?

You can create a new category using the /wp-json/wp/v2/categories endpoint in the WordPress REST API. The endpoint supports POST requests for creating new categories.

Here’s a Python example using the requests library:

import requests
import json

url = 'https://yourwebsite.com/wp-json/wp/v2/categories'
headers = {'Content-Type': 'application/json'}
auth = ('username', 'password')  # replace with your username and password

data = {
    'name': 'My New Category',
    'description': 'This is my new category.',
}

response = requests.post(url, headers=headers, auth=auth, data=json.dumps(data))

if response.status_code == 201:
    category = response.json()
    print('New category ID:', category['id'])
    print('New category name:', category['name'])
else:
    print('Failed to create category. Status code:', response.status_code)

Replace 'https://yourwebsite.com' with your website URL, 'username' and 'password' with your username and password, and 'My New Category' and 'This is my new category.' with your desired category name and description.

This script will create a new category with the name "My New Category" and the description "This is my new category". and then print out the ID and name of the new category.

πŸ§‘β€πŸ’» Note: To be able to create categories, your user account needs to have the manage_categories permission.

What if the Category Already Exists?

If you attempt to create a category that already exists, the WordPress REST API will return a response with a 400 status code and a message indicating that the term already exists.

You can handle this in your Python script by checking the status code and the error message in the response. Here’s an example:

import requests
import json

url = 'https://yourwebsite.com/wp-json/wp/v2/categories'
headers = {'Content-Type': 'application/json'}
auth = ('username', 'password')  # replace with your username and password

data = {
    'name': 'My New Category',
    'description': 'This is my new category.',
}

response = requests.post(url, headers=headers, auth=auth, data=json.dumps(data))

if response.status_code == 201:
    category = response.json()
    print('New category ID:', category['id'])
    print('New category name:', category['name'])
elif response.status_code == 400 and response.json().get('code') == 'term_exists':
    print('Category already exists.')
else:
    print('Failed to create category. Status code:', response.status_code)

In this updated script, if a category already exists with the same name, the script will print "Category already exists".

Please note that you need to replace 'https://yourwebsite.com' with your website URL, and 'username' and 'password' with your username and password.