How to Automate WordPress using Python

Deepanshu Bhalla Add Comment

This tutorial explains how to use Python to automate tasks in WordPress. It includes various functions to perform tasks such as creating, extracting, updating and deleting WordPress posts, pages and media items (images) directly from Python.

WordPress API Integration in Python
Table of Contents

Authorization

The first step is to authenticate your API requests. WordPress needs authentication to verify user credentials. You will need your WordPress username and an application password or API token to generate a base64-encoded token.

To generate an Application Password for WordPress, log in to your WordPress dashboard, go to Users > Your Profile and then scroll down to the Application Passwords section. Enter a name for the application and click Add New Application Password to generate a password.
import requests
import base64

wp_site = "https://www.testsite.com"
wp_username = "xxxxxx@gmail.com"
wp_password = "xxxx xxxx xxxx xxxx xxxx xxxx"  # Application_Password

# Create the authorization token
wp_credentials = f"{wp_username}:{wp_password}"
wp_token = base64.b64encode(wp_credentials.encode()).decode()

Fetch WordPress posts/pages

The following function extracts a page or post from a WordPress site.


def wp_request(method, wp_site, endpoint, wp_token, data=None):
    api_url = f"{wp_site}{endpoint}"
    response = None
    
    wp_header = {
        'Authorization': f'Basic {wp_token}'
    }
    
    if method == 'GET':
        response = requests.get(api_url, headers=wp_header)
    elif method == 'POST':
        response = requests.post(api_url, headers=wp_header, json=data)
    elif method == 'PUT':
        response = requests.put(api_url, headers=wp_header, json=data)
    elif method == 'DELETE':
        response = requests.delete(api_url, headers=wp_header)

    return response

# Define the function to get content
def get_content(id=None, wp_site='', wp_token=None, content_type='posts'):
    endpoint = f"/wp-json/wp/v2/{content_type}" if id is None else f"/wp-json/wp/v2/{content_type}/{id}"
    response = wp_request('GET', wp_site, endpoint, wp_token)

    if response.status_code == 200:
        return response.json()
    else:
        raise Exception(f"Error fetching content: {response.status_code}, {response.text}")
        
posts = get_content(wp_site = wp_site, wp_token = wp_token, content_type = "posts")       
Arguments
  • id (optional) – The ID of the post or page to retrieve. If NULL, all posts/pages are fetched.
  • wp_site – URL of the WordPress site (e.g. "https://example.com").
  • wp_token – Authentication token.
  • content_type (optional) – The type of content to fetch either "posts" or "pages". Defaults to "posts".

You can use the argument id to fetch content of a specific post.


# Specific Post
page_id = 360
page_data = get_content(page_id, wp_site, wp_token = wp_token, content_type = "posts")

By default, the API returns a maximum of 100 posts per page. If you have a large blog with more than 100 posts, you can use the function below to extract all the WordPress posts.


def get_content_pagination(wp_site, wp_token, content_type='posts'):
    # Construct the API URL for the first page
    api_url = f"{wp_site}/wp-json/wp/v2/{content_type}?page=1&per_page=100"
    response = requests.get(api_url, headers={'Authorization': f'Basic {wp_token}'})

    # Get total pages from response headers
    total_pages = int(response.headers.get('X-WP-TotalPages', 0))

    current_page = 1
    all_page_items_json = []  # Initialize an empty list to store all items

    while current_page <= total_pages:
        api_url = f"{wp_site}/wp-json/wp/v2/{content_type}?page={current_page}&per_page=100"
        page_items = requests.get(api_url, headers={'Authorization': f'Basic {wp_token}'})
        page_items_json = page_items.json()

        # Append the current page's items to the list
        all_page_items_json.extend(page_items_json)
        current_page += 1

    return all_page_items_json

posts = get_content_pagination(wp_site, wp_token = wp_token)

You can set the argument content_type to "pages" to extract content of all the WordPress pages.


pages = get_content(wp_site = wp_site, wp_token = wp_token, content_type = "pages")

How to Create a New WordPress Post or Page

The following function creates a new post on a WordPress site.


def post_content(wp_site, wp_token, data, content_type='posts'):
    endpoint = f"/wp-json/wp/v2/{content_type}"
    response = wp_request('POST', wp_site, endpoint, wp_token, data)

    if response.status_code == 201:
        return response.json()  # Returns the parsed content
    else:
        raise Exception(f"Error creating content: {response.status_code}, {response.text}")


# Define the new post data
new_post = {
    'title': "New Post Title",
    'content': "This is the content of the new post.",
    'slug': "new-post-2024",
    'status': "publish"
}

# Call the post_content function to create the new post
created_post = post_content(wp_site=wp_site, wp_token=wp_token, data=new_post, content_type='posts')

# Print the created post response
print(created_post)

Note - You can also use HTML, CSS and JavaScript in the content argument for custom formatting and interactivity.

To create a new page on a WordPress site, use "pages" in the content_type argument.


new_page = {
    'title': "New Post Title",
    'content': "This is the content of the new post.",
    'slug': "new-post-2024",
    'status': "publish"
}

created_page = post_content(wp_site=wp_site, wp_token=wp_token, data=new_post, content_type='pages')

Update WordPress Page or Post

The following function modifies an existing page or post on a WordPress site.


def modify_content(id, wp_site, wp_token, data, content_type='posts'):
    endpoint = f"/wp-json/wp/v2/{content_type}/{id}"
    response = wp_request('PUT', wp_site, endpoint, wp_token, data)

    if response.status_code == 200:
        return response.json()  # Returns the parsed content
    else:
        raise Exception(f"Error updating content: {response.status_code}, {response.text}")


# Define the updated data for the page
page_id = created_page['id']
updated_data = {
    'title': "Updated Title2",
    'content': "This is the updated content 2."
}

# Call the modify_content function to update the page
updated_page = modify_content(page_id, wp_site, wp_token, data=updated_data, content_type='pages')

# Print the updated page response
print(updated_page)

Delete WordPress Page or Post

The function delete_content() deletes a specific page or post on a WordPress site using the REST API.


def delete_content(id, wp_site, wp_token, content_type='posts'):
    endpoint = f"/wp-json/wp/v2/{content_type}/{id}"
    response = wp_request('DELETE', wp_site, endpoint, wp_token)

    if response.status_code == 200:
        return response.json()  # Returns the parsed content (if any)
    else:
        raise Exception(f"Error deleting content: {response.status_code}, {response.text}")

# Access the ID of the created post
page_id = created_post['id']
delete_response = delete_content(page_id, wp_site, wp_token, content_type='posts')

# Print the delete response
print(delete_response)

Get Media Items from WordPress

This function get_media() fetches a list of media items (images/videos) from a WordPress site.


def get_media(wp_site, wp_token, per_page=10, page=1):
    # Prepare the API endpoint for fetching media items
    api_url = f"{wp_site}/wp-json/wp/v2/media?per_page={per_page}&page={page}"

    # Send the GET request to retrieve media items
    response = requests.get(api_url, headers={'Authorization': f'Basic {wp_token}'})

    if response.status_code == 200:
        media_items = response.json()  # Parse the JSON response
        return media_items
    else:
        raise Exception(f"Error fetching media items: {response.status_code}, {response.text}")

# Call the function to get media items
media_items = get_media(wp_site, wp_token, per_page=30, page=1)

# Print the retrieved media items
print(media_items)
Arguments
  • wp_site – URL of the WordPress site.
  • wp_header – Authentication header.
  • per_page (optional) – Number of media items to retrieve per page. Defaults to 10.
  • page (optional) – The page number of media items to retrieve. Defaults to 1.

Delete Media Items from WordPress

The following function deletes a specific media item like image from the WordPress media library.


def delete_media(media_id, wp_site, wp_token, force=True):
    # Prepare the API endpoint for deleting media
    api_url = f"{wp_site}/wp-json/wp/v2/media/{media_id}?force={str(force).lower()}"

    # Send the DELETE request to remove the media
    response = requests.delete(api_url, headers={'Authorization': f'Basic {wp_token}'})

    if response.status_code == 200:
        print("Media deleted successfully.")
        return response.json()  # Return the parsed response
    else:
        raise Exception(f"Error deleting media: {response.status_code}, {response.text}")

# Specify the media ID to delete
media_id = 752

# Call the function to delete the media
deleted_media = delete_media(media_id, wp_site, wp_token, force=True)

# Print the deleted media response
print(deleted_media)

Upload Image to WordPress Media Library

The following function uploads an image from the local drive to the WordPress media library.


def upload_media(image_path, wp_site, wp_token):
    # Prepare the API endpoint for media uploads
    api_url = f"{wp_site}/wp-json/wp/v2/media"

    # Open the image file from the local drive
    with open(image_path, 'rb') as image_file:
        # Set the headers for the request, including Content-Disposition
        filename = image_path.split('/')[-1]  # Extract filename from path
        headers = {
            'Authorization': f'Basic {wp_token}',
            'Content-Disposition': f'attachment; filename="{filename}"'
        }

        # Send the POST request to upload the image
        response = requests.post(api_url, headers=headers, files={'file': image_file})

    if response.status_code == 201:  # Status 201 means created
        print("Image uploaded successfully.")
        return response.json()  # Return the parsed response
    else:
        raise Exception(f"Error uploading image: {response.status_code}, {response.text}")

# Specify the image path to upload
image_path = "C:/Users/deepa/Downloads/NVDA.png"

# Call the function to upload the image
uploaded_image = upload_media(image_path, wp_site, wp_token)

# Print the uploaded image response
print(uploaded_image)
Related Posts
Spread the Word!
Share
About Author:
Deepanshu Bhalla

Deepanshu founded ListenData with a simple objective - Make analytics easy to understand and follow. He has over 10 years of experience in data science. During his tenure, he worked with global clients in various domains like Banking, Insurance, Private Equity, Telecom and HR.

Post Comment 0 Response to "How to Automate WordPress using Python"
Next →