Automating SEO Optimized Content Creation with OpenAI and WordPress API using Python
Tags: openai, python, wordpress, seo
Published: 2023-08-24 12:56:28

## Introduction:

In the digital age, content is king. But creating SEO-optimized content that stands out can be a time-consuming process. What if we could automate this process, from keyword extraction to content publication, using the power of OpenAI and the WordPress API? In this article, we'll explore a project that does just that, streamlining the content creation process and ensuring SEO optimization every step of the way.

## Process: 

### 1. Harnessing OpenAI for Keyword Extraction:

#### a. The Power of OpenAI:

OpenAI's models, especially GPT variants, are adept at understanding context and generating relevant content. This capability can be harnessed to extract keywords related to specific fields or topics.

We're operating under the assumption that you've already set up your Python project and have a main.py file in place.
You'll need to sign up with OpenAI and obtain an API key. Do take note of OpenAI's pricing structure; costs vary depending on the engine selected, the number of requests made, the length of each request, among other factors.

After setting up your OpenAI account...

```
import openai

OPENAI_KEY = ### API Key## 
```


#### b. Process Flow:

Input a core topic or field into the OpenAI model.
The model returns a list of relevant keywords that resonate with the topic.

Next, you'll need to craft a prompt to retrieve keywords relevant to your topics. There are several effective OpenAI prompts designed specifically for extracting SEO keywords.


```
def replace_placeholder(string, keyword):
    if isinstance(keyword, tuple):
        keyword = keyword[0]
    placeholder = re.search(r'\[.*?\]', string)
    return string.replace(placeholder.group(0), keyword) if placeholder else string

def chat_content(keyword, prompt):
    openai.api_key = OPENAI_KEY
    prompt_data = replace_placeholder(prompt, keyword)
    response = openai.ChatCompletion.create(
        model="gpt-3.5-turbo",
        messages=[
            {"role": "system", "content": "You are a helpful assistant."},
            {"role": "user", "content": prompt_data}
        ]
    )
    return response['choices'][0]['message']['content']

def keyword_research:
    lsi_keywords = []
    keywords_list = ['ecommerce platofrm']

    keyword_research = ["Generate 10 Most Popular Keywords For The Topic Of [Your Topic or Seed keyword]., without numbering in a simple list separated by comma",
]

    for topic in keyword_research:
        for keyword in keywords_list:
            formatted_prompt = topic.replace('[Your Topic or Seed keyword]', keyword)
            assistant_reply = chat_content(keyword,formatted_prompt)
            lines = assistant_reply[0].split(',')
            keywords = [line.strip() for line in lines if line.strip()]
            lsi_keywords.append(keywords)
    return lsi_keywords


```

### 2. Crafting SEO-Optimized Content:

#### a. Title Generation:
Using the extracted keywords, OpenAI can craft catchy and SEO-friendly titles that grab the reader's attention.

#### b. Meta Description Creation:
A concise meta description is crucial for SEO. OpenAI can generate a brief summary that encapsulates the essence of the article, ensuring it's optimized for search engines.

#### c. Crafting the Introduction:
The introduction sets the tone for the entire article. Using the keywords, OpenAI can create an engaging and relevant introduction that hooks the reader.

#### d. Content Generation:
With the keywords as a guide, OpenAI can generate the bulk of the content, ensuring it's informative, relevant, and SEO-optimized.

```
def create_content:
    on_page_seo = [
    "Generate a single Eye-catching And Click-worthy Titles about [Your Article or Blog Post].",
"Generate 10 Most Popular Keywords For The Topic Of [Your Topic or Seed keyword]. Separated by comma",
    "Make the blog post titled [title] more catchy.", 
    "Generate a meta descriptions about [Your Article or Blog Post] with less than 160 characters",
    "Summarize my content and generate 5 brief headlines about [Your Content].",
    "Create Engaging & Informative Content", #Write a blog post about [Your Topic].
]
    field_mapping = {
            0: 'title',
            1: 'keywords',
            2: 'meta_description',
            3: 'headings',
            4: 'content',
        }
     content_dict = {}

     for index, prompt in enumerate(on_page_seo):
        if index in field_mapping:
            content = chat_content(lsi_topic.lsi_keyword, prompt)
            content_dict[field_mapping[index]] = content
    return content_dict

```

### 3. Seamless Integration with WordPress API:


#### a. The WordPress API:

The WordPress REST API provides an interface to interact with your WordPress site programmatically. This means you can create, read, update, and delete content without ever accessing the WordPress dashboard.

#### b. Process Flow:

Once the content is ready, it's formatted into a structure suitable for the WordPress API.

Using a simple Python script or any preferred language, the content is pushed to the WordPress site via the API.
The article is saved as a draft, allowing for any final reviews or edits before publication.

Assuming you've already set up WordPress, you'll need to obtain the WordPress API key for a user with at least an 'editor' role. From the WordPress admin panel, generate an application password, which will appear in this format: xxxx xxxx xxxx xxxx.

```

def structure_for_wordpress(organized_content, image_url):
    return f"""
    <article>

        <figure>
            <img src="{image_url}"">
        </figure>
        <p>{organized_content['content_intro']}</p>

        <section>
            <h3>Overview</h3>
            <p>{organized_content['headings']}</p>
        </section>

        <section>
            <h3>Details</h3>
            <p>{organized_content['content']}</p>
        </section>

        <section>
            <h3>FAQs</h3>
            <p>{organized_content['faq']}</p>
        </section>

        <section>
            <h3>Conclusion</h3>
            <p>{organized_content['content_conclusion']}</p>
        </section>
    </article>
    """
def fetch_image_from_unsplash(description):
    API_URL = 'https://api.unsplash.com/search/photos'
    API_KEY = 'xxxxxx'

    response = requests.get(API_URL, params={"query": description, "client_id": API_KEY})
    if response.status_code == 200 and 'results' in response.json():
        return response.json()['results'][0]['urls']['regular']
    return None

def publish_to_wordpress(title, content):
    WP_URL_HOST = "https://example.com"
    user_auth_url = f'{WP_URL_HOST}/wp-json/jwt-auth/v2/users/me'
    WP_URL = f"{settings.WP_URL_HOST}/wp-json/wp/v2"
    WP_USER = "XXXX"
    WP_PASS = 

    headers = {
        "Content-Type": "application/json",
        "Authorization": f"Basic {base64.b64encode(f'{WP_USER}:{WP_PASS}'.encode()).decode('utf-8')}"
    }
    post = {
        "title": title,
        "content": content,
        "status": "publish"  # Set to 'draft' if you want to review the post before publishing
    }

    response = requests.post(f"{WP_URL}/posts", headers=headers, json=post)

    return response.status_code == 200

def post_content:
    field_mapping = {
            0: 'title',
            1: 'keywords',
            2: 'meta_description',
            3: 'headings',
            4: 'content',
        }
    for field_index, field_name in field_mapping.items():
        content = getattr(record, field_name)
        setattr(record, field_name, content)
        organized_content = {field_name: getattr(record, field_name) for field_index, field_name in
                             field_mapping.items()}
    image_url = fetch_image_from_unsplash(organized_content['meta_description'])
    post_wp = structure_for_wordpress(organized_content, image_url)
    wp_response = publish_to_wordpress(title=organized_content['optimized_title'], content=post_wp)

    return wp_response
```

Now need to call each specific function when running the main.py to execute each task

### Conclusion:
The fusion of OpenAI's content generation capabilities with the WordPress API offers a powerful tool for content creators and digital marketers. By automating the SEO content creation process, we can ensure consistency, quality, and optimization, allowing creators to focus on other crucial aspects of their digital strategy. As technology continues to evolve, such integrations promise a future where content creation is more streamlined, efficient, and effective.