This Python script enables you to effortlessly generate multiple WordPress posts with AI-generated text content created by OpenAI's current ChatGPT "gpt-3.5-turbo" model. And posted directly to WordPress using the WordPress Rest API.
The content is based on a list of prompts in CSV format, making it a convenient solution for creating diverse and engaging posts on your WordPress site.
Getting Started:
Please note the following limitations and customisation options:
The python script is in 2 parts. The first is the programmatic content created by ChatGPT API and the second part is a WordPress auto poster using the WordPress Rest API.
Here are the libraries that you will need:
The next part of the script - OpenAI API to generate content
This code is a simple and easy-to-understand Python script that utilizes the OpenAI API to generate content for a list of prompts and create a dataframe containing the generated responses. Here's a step-by-step explanation:
The last part - WordPress REST API to create posts using the generated content
This code snippet demonstrates how to connect to a WordPress site using the REST API and create posts using the generated content. Here's a step-by-step explanation:
Google Colab copy of the ChatGPT to WordPress AutoPoster Python Script
If you're interested in obtaining a complete copy of the ChatGPT to WordPress AutoPoster Python Script, you can easily do so by accessing the provided Google Colab notebook. This notebook contains the full script, allowing you to run, modify, and experiment with the code directly in a cloud-based environment.
To access the Google Colab ChatGPT to WordPress AutoPoster Python Script, simply follow this link: https://colab.research.google.com/drive/1ajE08rGqnx7FH7GF52Ujv-vqC5qyySua?usp=sharing
Once you have the notebook open, you can start using the script by following these steps:
Here is that link again: https://colab.research.google.com/drive/1ajE08rGqnx7FH7GF52Ujv-vqC5qyySua?usp=sharing
Thanks for reading, if you need any help customising the python script, then comment below. If you need a customised version of the script, get in touch, you can hire me to build you a customised version. FYI - I used ChatGPT to help me write this post by explaining what the script does.
The content is based on a list of prompts in CSV format, making it a convenient solution for creating diverse and engaging posts on your WordPress site.
Getting Started:
- Set up your OpenAI API Key.
- Provide a list of prompts in a CSV file (1 per line), with the row head being the Title.
- Configure your WordPress API credentials.
- Click RUN for each cell.
- Clear Dataframes after each successful script run.
Please note the following limitations and customisation options:
- The current script only sets 'post_title' and 'post_content'. If you need additional WordPress schemas, you'll need to modify the script accordingly. The default author ID is set to '1', and no category has been assigned.
- The script generates a single prompt request with a maximum of 100 tokens. To increase the output or provide more context to the prompt requests, you can adjust the API request parameters. For more information on how to do this, consult the official OpenAI documentation: https://platform.openai.com/docs/guides/chat.
The python script is in 2 parts. The first is the programmatic content created by ChatGPT API and the second part is a WordPress auto poster using the WordPress Rest API.
Here are the libraries that you will need:
Code:
# Import modules
#!pip install --upgrade pip (uncomment if OpenAI does not install)
#!pip install openai
import openai
import pandas as pd
import requests
import base64
import csv
import json
from tqdm.notebook import tqdm
The next part of the script - OpenAI API to generate content
This code is a simple and easy-to-understand Python script that utilizes the OpenAI API to generate content for a list of prompts and create a dataframe containing the generated responses. Here's a step-by-step explanation:
- Set up the OpenAI API key: The OpenAI API key is stored in the variable openai.api_key. Replace the empty string after "sk-" with your actual API key.
- Import the list of prompts: The code reads a CSV file containing the prompts from the specified URL using pandas and stores the data in a DataFrame df.
- Initialize empty lists: Two empty lists, prompts_list and responses_list, are created to store the prompts and their corresponding AI-generated responses.
- Loop through the list of prompts: The code iterates through each row of the DataFrame df, extracts the "Title" column's value, and appends it to the prompts_list.
- Set up the prompt response parameters: For each prompt, the script makes an API call to the OpenAI ChatCompletion API using the "gpt-3.5-turbo" model with a maximum of 100 tokens per response.
- Extract the response: The response from the API call is stored in the response variable after stripping any unnecessary whitespace.
- Store the response in the responses list: The generated response is appended to the responses_list.
- Monitor output in real-time: The script prints the prompt (Title) and its corresponding AI-generated response to the console, allowing you to monitor the progress of the content generated.
- Create a DataFrame for the results: The prompts_list and responses_list are combined into a dictionary, which is then used to create a new DataFrame df.
- Print the final DataFrame: The completed DataFrame containing the prompts (post_title) and their corresponding AI-generated responses (post_content) is printed.
Code:
# Your Open AI API Key
openai.api_key = "sk-"
# Fetch the list of prompts
df = pd.read_csv("https://sitebee.uk/questions.csv")
# Create the empty lists
prompts_list = []
responses_list = []
# Loop through the list of prompts
for index, row in tqdm(df.iterrows()):
prompts = (row["Title"])
prompts_list.append(prompts)
# Prompt response parameters
completion = openai.ChatCompletion.create(
model="gpt-3.5-turbo",
max_tokens=100,
messages=[{"role": "user", "content": prompts}]
)
# Prompt response output
response = completion.choices[0].message.content.strip()
responses_list.append(response)
# Realtime output monitoring
print("\n")
print(row["Title"])
print(completion.choices[0].message.content)
# Create dataframe
data = {"post_title": prompts_list, "post_content": responses_list}
df = pd.DataFrame(data)
# Print the dataframe
df
The last part - WordPress REST API to create posts using the generated content
This code snippet demonstrates how to connect to a WordPress site using the REST API and create posts using the generated content. Here's a step-by-step explanation:
- Set up WordPress REST API credentials: Provide your WordPress username and password, as well as the URL of your site's REST API endpoint. The wp_connection variable combines the username and password, which is then encoded in Base64 format and stored in the token variable.
- Authenticate with WordPress: The headers dictionary is created with the 'Authorization' key, containing the "Basic" authentication scheme, followed by the Base64 encoded token.
- Define the function to create a WordPress post: The wp_post_insert function accepts two parameters: post_title and post_content. The function creates a dictionary called post containing the required WordPress post schemas such as title, status, content, author, and format. You can add or remove post schemas according to your needs.
- Send the post creation request to WordPress: Inside the wp_post_insert function, the code sends a POST request to the WordPress REST API endpoint with the headers for authentication and the JSON post data. The endpoint URL is constructed by appending '/posts' to the URL variable.
- Loop through the DataFrame and create WordPress posts: The script iterates through each row of the DataFrame df and calls the wp_post_insert function with the "post_title" and "post_content" values from the DataFrame.
Code:
# WordPress Rest API credentials
user = 'username'
password = '7243 ieMV hKPS VqqZ MQxG fMKL'
url = 'https://airwolf.dev/wp/wp-json/wp/v2'
wp_connection = user + ':' + password
token = base64.b64encode(wp_connection.encode())
# Authenticate WordPress
headers = {'Authorization': 'Basic ' + token.decode('utf-8')}
# (add/remove post schemas to suit your needs)
def wp_post_insert(post_title, post_content):
post = {'title': post_title,
'status': 'publish',
'content': post_content,
'author': '1',
'format': 'standard'
}
wp_post_insert_request = requests.post(url + '/posts', headers=headers, json=post)
# Loop through the dataframe prompts/responses post directly to WordPress
for index, row in tqdm(df.iterrows()):
# Add or remove WordPress post schemas variables below
wp_post_insert(row["post_title"], row["post_content"])
Google Colab copy of the ChatGPT to WordPress AutoPoster Python Script
If you're interested in obtaining a complete copy of the ChatGPT to WordPress AutoPoster Python Script, you can easily do so by accessing the provided Google Colab notebook. This notebook contains the full script, allowing you to run, modify, and experiment with the code directly in a cloud-based environment.
To access the Google Colab ChatGPT to WordPress AutoPoster Python Script, simply follow this link: https://colab.research.google.com/drive/1ajE08rGqnx7FH7GF52Ujv-vqC5qyySua?usp=sharing
Once you have the notebook open, you can start using the script by following these steps:
- Make a copy of the notebook: To create your personal copy, click on "File" in the top left corner of the Google Colab interface and select "Save a copy in Drive." This will create a duplicate of the notebook in your Google Drive.
- Edit the script: In your copy of the notebook, you can modify the script to suit your specific needs. Update the necessary variables, such as the API keys, WordPress credentials, and CSV file URL, to match your configuration.
- Run the script: Execute the cells in the notebook to test the script and generate content for your WordPress site. Make sure to follow the instructions provided in the comments to ensure smooth execution.
- Make further modifications: If needed, you can customise the script to add more functionality, such as support for additional WordPress post schemas or adjustments to the OpenAI API call parameters. Visit this URL to see the list of schemas for /posts API endpoint - https://developer.wordpress.org/rest-api/reference/posts/
Here is that link again: https://colab.research.google.com/drive/1ajE08rGqnx7FH7GF52Ujv-vqC5qyySua?usp=sharing
Thanks for reading, if you need any help customising the python script, then comment below. If you need a customised version of the script, get in touch, you can hire me to build you a customised version. FYI - I used ChatGPT to help me write this post by explaining what the script does.
Last edited: