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, comments and media items (images) directly from Python.
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" 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()
Posts
List WordPress Posts
The following function extracts all posts 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")
- 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
post_id = 360
post_data = get_content(post_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)
Create a New WordPress Post
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.
Update WordPress Post
The following function modifies an existing 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 post
post_id = created_post['id']
updated_data = {
'title': "Updated Title2",
'content': "This is the updated content 2."
}
# Call the modify_content function to update the post
updated_post = modify_content(post_id, wp_site, wp_token, data=updated_data)
# Print the updated post response
print(updated_post)
Delete WordPress Post
The function delete_content()
deletes a specific 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
post_id = created_post['id']
delete_response = delete_content(post_id, wp_site, wp_token, content_type='posts')
# Print the delete response
print(delete_response)
Pages
List WordPress Pages
You can set the argument content_type
to "pages" to extract content of all the WordPress pages.
pages = get_content_pagination(wp_site = wp_site, wp_token = wp_token, content_type = "pages")
You can use the argument id
to fetch content of a specific page.
# Specific Page
page_id = 802
page_data = get_content(page_id, wp_site, wp_token = wp_token, content_type = "pages")
Create a New WordPress Page
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
The following function modifies an existing page on a WordPress site.
# 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
The function delete_content()
deletes a specific page on a WordPress site using the REST API.
# Access the ID of the created post
page_id = created_page['id']
delete_response = delete_content(page_id, wp_site, wp_token, content_type='pages')
# Print the delete response
print(delete_response)
Media Items (Images)
Get Media Items from WordPress
The following function fetches a list of media items (images/videos) from a WordPress site.
media_items = get_content_pagination(wp_site = wp_site, wp_token = wp_token, content_type = "media")
# Print the retrieved media items
print(media_items)
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)
Comments
Get Comments from WordPress
The following function extracts comments from a WordPress site.
comments = get_content_pagination(wp_site, wp_token = wp_token, content_type = "comments")
Delete Comments from WordPress
The function delete_comment
deletes comments from a WordPress site.
def delete_comment(comment_id, wp_site, wp_token, force=True):
# Prepare the API endpoint for deleting comment
api_url = f"{wp_site}/wp-json/wp/v2/comments/{comment_id}?force={str(force).lower()}"
# Send the DELETE request to remove the comment
response = requests.delete(api_url, headers={'Authorization': f'Basic {wp_token}'})
if response.status_code == 200:
print("comment deleted successfully.")
return response.json() # Return the parsed response
else:
raise Exception(f"Error deleting comment: {response.status_code}, {response.text}")
# Specify the comment ID to delete
comment_id = 8
# Call the function to delete the comment
deleted_comment = delete_comment(comment_id, wp_site, wp_token, force=True)
# Print the deleted comment response
print(deleted_comment)
How to Create a New Comment
The following function creates a new comment on a WordPress site.
new_comment = {
'post': 351,
'content': "this is a new comment",
'author_name': "amit",
'author_email': "amit@gmail.com"
}
# Call the post_content function to create the new comment
created_comment = post_content(wp_site=wp_site, wp_token=wp_token, data=new_comment, content_type='comments')
# Print the created comment response
print(created_comment)
How to Update Comment
The following function modifies an existing comment on a WordPress site.
# Define the updated data for the comment
comment_id = 13
updated_data = {
'post': 351,
'content': "this is a new comment2",
'author_name': "amit",
'author_email': "amit@gmail.com"
}
# Call the modify_content function to update the comment
updated_comment = modify_content(comment_id, wp_site, wp_token, data=updated_data, content_type='comments')
# Print the updated comment response
print(updated_comment)
Share Share Tweet