• Home
  • Python Script - ChatGPT to WordPress AutoPoster


    Staff member
    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:
    1. Set up your OpenAI API Key.
    2. Provide a list of prompts in a CSV file (1 per line), with the row head being the Title.
    3. Configure your WordPress API credentials.
    4. Click RUN for each cell.
    5. Clear Dataframes after each successful script run.
    By utilising this script, you can automate the process of programmatically creating WordPress posts, ensuring a steady flow of unique and interesting content for your readers.

    Please note the following limitations and customisation options:
    1. 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.
    2. 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.
    By customising the script to suit your needs, you can unlock the full potential of the ChatGPT to WordPress AutoPoster and take your content generation to new heights. This versatile tool is perfect for bloggers, content creators, and digital marketers looking to streamline their content creation process and maintain a consistent presence on their WordPress site.

    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:
    # 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:
    1. 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.
    2. 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.
    3. Initialize empty lists: Two empty lists, prompts_list and responses_list, are created to store the prompts and their corresponding AI-generated responses.
    4. 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.
    5. 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.
    6. Extract the response: The response from the API call is stored in the response variable after stripping any unnecessary whitespace.
    7. Store the response in the responses list: The generated response is appended to the responses_list.
    8. 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.
    9. 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.
    10. Print the final DataFrame: The completed DataFrame containing the prompts (post_title) and their corresponding AI-generated responses (post_content) is printed.
    The code is below:
    # 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"])
    # Prompt response parameters
     completion = openai.ChatCompletion.create(
      messages=[{"role": "user", "content": prompts}]
    # Prompt response output
     response = completion.choices[0].message.content.strip()
    # Realtime output monitoring
    # Create dataframe
    data = {"post_title": prompts_list, "post_content": responses_list}
    df = pd.DataFrame(data)
    # Print the dataframe

    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:
    1. 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.
    2. Authenticate with WordPress: The headers dictionary is created with the 'Authorization' key, containing the "Basic" authentication scheme, followed by the Base64 encoded token.
    3. 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.
    4. 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.
    5. 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.
    By following these steps, the code snippet will create and publish WordPress posts using the AI-generated content and the specified post schemas. The code is below:

    # 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:
    1. 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.
    2. 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.
    3. 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.
    4. 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/
    By following these steps, you'll be able to create a personalised copy of the ChatGPT to WordPress AutoPoster Python Script and tailor it to meet your content generation needs.

    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: