Automate Your Blog Post With This SEO-Optimized OpenAI Script

    Published on:

    Are you exhausted from spending countless hours crafting and optimizing your blog posts for search engines? Do you long for a simpler and more efficient way to create SEO-optimized content that includes internal links and automatically schedules the article to be posted on your website? Look no further! In this article, we will delve into the world of automating your blog post creation process using an SEO-optimized OpenAI script. With this powerful tool at your disposal, you can save precious time and energy while still producing high-quality, engaging content that ranks well in search results. Here’s a step-by-step guide to get started.

    1. Introduction

    Blogging has become an integral part of online communication, allowing individuals and businesses to share their knowledge, promote products or services, and connect with their target audience. However, the process of creating and optimizing blog posts can be time-consuming and laborious. That’s where automation comes in handy.

    2. Get Your OpenAI Key

    To begin, you’ll need to obtain your OpenAI key. Visit the OpenAI platform at and navigate to “View API keys.” Create a new secret key, providing it with a descriptive name, and copy the key for later use.

    3. Setting Up Your Environment

    Open your preferred code editor, such as Visual Studio Code, and create a new file with a .py extension. Save it with a relevant name, like “” Next, copy the script provided below and paste it into your file. Make sure to replace 'Add your OpenAI key' with your actual OpenAI key obtained in the previous step.

    import os
    import openai
    import requests
    import pandas as pd
    from PIL import Image
    from io import BytesIO
    from tqdm import tqdm 
    # Set OpenAI API key
    openai.api_key = 'Your OpenAi Key'
    print("OpenAI API key set...")
    # Function to generate a clickable title using GPT-4
    def generate_clickable_title(title):
        print("Generating clickable title...")
        prompt = f"Generate a catchy and clickable title for a blog post based on the titled '{title} Maximum 60 characters'."
        response = openai.ChatCompletion.create(
            model="gpt-3.5-turbo",  # Updated to GPT-4
                {"role": "system", "content": "You are a helpful assistant."},
                {"role": "user", "content": prompt}
        clickable_title = response['choices'][0]['message']['content'].strip()
        clickable_title = clickable_title.replace('"', '')  # Remove double quotes
        print("Clickable title generated...")
        return clickable_title
    # Function to generate blog post using GPT-4
    def generate_blog_post(row):
        print("Generating blog post...")
        original_title = row['blog post title']
        internal_links = row['links']
        # Generate a clickable title
        title = generate_clickable_title(original_title)
        # Prepare a prompt for GPT-4.
        prompt = f'Write seo friendly content with word length of 1200 words, with considering the internal links "{internal_links}" Use the internal links in the content make it seo friendly, use up to 5 internal links, Consider SEO ranking factors'
        # Generate the blog post using GPT-4.
        response = openai.ChatCompletion.create(
            model="gpt-3.5-turbo",  # Updated to GPT-4
                {"role": "system", "content": "You are a WordPress Writer. You write articles with introductions, brands, and conclusons, each section should have some content. Under each product name you ALWAYS put an embeded iframe link. You only write in HTML. Including headings, subheadings etc. You also always embed amazon iframe links after every mention of the brand"},
                {"role": "user", "content": prompt}
        blog_post = response['choices'][0]['message']['content'].strip()
        print("Blog post generated...")
        return title, blog_post
    # Function to upload post to WordPress
    def upload_to_wordpress(title, content):
        print("Uploading post to WordPress...")
        url = ""
        headers = {
            "Authorization": "Bearer your auth code",
        data = {
            "title": title,
            "content": content,
            "status": "publish",
        response =, headers=headers, json=data)
        print("Post uploaded to WordPress...")
        return response.json()
    # Function to generate image using DALL-E
    def generate_image(prompt):
        print("Generating image using DALL-E...")
        response = openai.Image.create(
        image_url = response['data'][0]['url']
        print("Image generated...")
        return image_url
    # Function to download and save image
    def save_image(image_url, filename):
        print("Saving image...")
        response = requests.get(image_url)
        image =
        print("Image saved...")
    # Function to upload image to WordPress
    def upload_image_to_wordpress(filename):
        url = ""
        headers = {
            "Authorization": "Bearer your auth code",
            "Content-Disposition": f"attachment; filename={filename}",
            "Content-Type": "image/jpeg",
        with open(filename, "rb") as image_file:
            response =, headers=headers, data=image_file)
        return response.json()  # Ensure .json() method is called
    # Load CSV
    print("Loading CSV...")
    df = pd.read_csv('file.csv')
    # Select the first row
    first_row = df.iloc[0]
    # Generate blog post for the first row
    print("Generating blog post...")
    title, blog_content = generate_blog_post(first_row)
    print("Blog post generated...")
    # Generate image using DALL-E
    print("Generating image...")
    image_prompt = "A patterned repeated background image-only with '{title}'"  # Replace this with the appropriate prompt for your blog post
    image_url = generate_image(image_prompt)
    # Save the generated image to your local system
    print("Saving image...")
    filename = "generated_image.jpg"
    save_image(image_url, filename)
    print("Image saved...")
    # Upload the image to WordPress
    print("Uploading image to WordPress...")
    uploaded_image = upload_image_to_wordpress(filename)
    print(f"Uploaded image: {uploaded_image}")  # Debugging line
    print("Image uploaded to WordPress...")
    # Add the uploaded image URL to the blog post content
    image_url = uploaded_image['source_url']
    blog_content_with_image = f'<img src="{image_url}" style="max-width:100%;height:auto;" alt="{image_prompt}"><br>{blog_content}'
    # Upload the blog post with the image
    print("Uploading post to WordPress...")
    upload_to_wordpress(title, blog_content_with_image)
    print("Post uploaded to WordPress...")

    4. JWT Plugin Installation

    After pasting the above script in your file and changing all of the marked fields i.e. OpenAi Key, auth code, and website name. Open your WordPress website and install and activate a plugin. For installation go to Plugins > Add New, then search for JWT Authentication for WP REST API, and click Install Now.

    JWT Authentication for WP REST API

    5. Changes in the Hosting Server

    Afterward, you need to configure your .htaccess file. Add the following lines to your .htaccess file, located in the root folder of your WordPress installation:

    RewriteEngine on
    RewriteCond %{HTTP:Authorization} ^(.*)
    RewriteRule ^(.*) - [E=HTTP_AUTHORIZATION:%1]

    Next, open the wp-config.php file, also located in the root folder of your WordPress installation, and add the following lines:

    Replace ‘your-top-secret-key’ with a strong secret key. Generate a secret key from here

    define('JWT_AUTH_SECRET_KEY', 'dfj$S>=$:l$%nY*$k;X$tSV,R*=#a7Hdneen+[#9$fz):46[0~-V/=zm^S{n}q_v')');
    define('JWT_AUTH_CORS_ENABLE', true); 

    Now open the command prompt. Change to “your website URL”, username to your website “login name”, and password to your website “password”.

    This will return a token that you can use in your Authorization header.

    curl -X POST -d "username=admin&password=admin"

    Now add that authorization code in the Python code where it asks for your_auth_code.

    def upload_image_to_wordpress(filename):
        url = ""
        headers = {
            "Authorization": "Bearer your_auth_code",
            "Content-Disposition": f"attachment; filename={filename}",
            "Content-Type": "image/jpeg",
        with open(filename, "rb") as image_file:
            response =, headers=headers, data=image_file)
        return response.json()  # Ensure .json() method is called

    After completing the modifications to the script and installing the JWT extension, please proceed with the following steps to ensure a seamless execution:

    1. Download the CSV file and place it in the same folder where your Python script is located. Modify the CSV file according to your requirements, including the blog title and internal links.
    2. Open a new terminal within your Visual Studio Code editor and navigate to the directory where you have saved the Python script file and the CSV file.
    3. In the terminal, execute the following command: python
    4. Once the command is executed, the script will generate the blog post content based on the provided inputs and proceed to upload it to your WordPress website.

    By following these steps, the script will efficiently generate and upload the blog post to your WordPress site.

    6. Conclusion

    Automating your blog post creation process with an SEO-optimized OpenAI script can be a game-changer. By leveraging OpenAI’s powerful language models, you can save time and effort while producing high-quality, engaging content that ranks well in search engines. From generating clickable titles to creating SEO-optimized blog posts and even incorporating visually appealing images, this script provides a comprehensive solution for your blogging needs.

    7. FAQs

    Q1: Can I use this script with platforms other than WordPress?

    A1: While this script is designed for WordPress websites, you can modify it to work with other platforms by adapting the code responsible for uploading the blog post and images.

    Q2: How long does it take to generate a blog post using this script?

    A2: The time required depends on various factors, including the length of the blog post and the complexity of the content generation. However, using OpenAI’s GPT-4 model ensures efficient and speedy results.

    Q3: Are there any limitations or considerations I should be aware of when using this script?

    A3: It’s important to stay within the usage limits of your OpenAI plan. Additionally, ensure that you follow ethical guidelines and comply with any applicable legal requirements when using OpenAI’s services.

    By automating your blog post creation process with this SEO-optimized OpenAI script, you can elevate your blogging experience to new heights. Embrace the power of automation and create compelling content that resonates with your audience while maximizing your search engine visibility. Happy blogging!

    Please note that the script and instructions provided in this article are for illustrative purposes. Be sure to adapt them to your specific requirements and follow best practices for security and compliance. If you have any questions or need assistance with the script or any other topic, feel free to ask.

    Read more: How to Use Chat GPT: A Simple Guide for Beginners


    Leave a Reply

    Please enter your comment!
    Please enter your name here