ChatGPT API AI 自動寫文章 + WordPress 自動生成文章完整教學(新手也能操作)

ChatGPT API AI 自動寫文章 + WordPress 自動生成文章完整教學

本篇完整教學如何使用 ChatGPT API AI 自動生成文章,並自動發佈到 WordPress。你將學會兩種 API 呼叫方式、文章 HTML 轉換與格式化,並搭配 WordPress REST API 自動發佈。教學流程清楚、新手也能快速完成,提升網站內容產出效率與 SEO 表現。

步驟一:選擇 API 呼叫方式

本步驟只需選擇一種方式執行,不需要全部執行。完成後會取得 AI 生成文章內容,提供自動化或網站整合兩種選擇。

可參考相關文章:AI 生成工具Python API 範例

方法一:Python 呼叫 API

import os
import openai

try:
    openai.api_key = os.getenv("OPENAI_API_KEY")
    prompt = "請生成完整 WordPress HTML 文章內容"
    response = openai.ChatCompletion.create(
        model="gpt-4",
        messages=[{"role": "user", "content": prompt}]
    )
    article_content = response.choices[0].message.get('content')
    with open("article_raw.txt", "w", encoding="utf-8") as f:
        f.write(article_content)
    print(article_content)
except Exception as e:
    print("API 呼叫錯誤:", e)

方法二:Node.js 呼叫 API

const { OpenAIApi, Configuration } = require("openai");
const fs = require("fs");

const configuration = new Configuration({ apiKey: process.env.OPENAI_API_KEY });
const openai = new OpenAIApi(configuration);

async function generateArticle() {
  try {
    const response = await openai.chat.completions.create({
      model: "gpt-4",
      messages: [{ role: "user", content: "請生成完整 WordPress HTML 文章內容" }]
    });
    const article_content = response.data.choices[0].message.content;
    fs.writeFileSync("article_raw.txt", article_content, { encoding: "utf-8" });
    console.log(article_content);
  } catch (error) {
    console.error("API 呼叫失敗:", error);
  }
}
generateArticle();

步驟二:文章轉換與格式化

若 API 回傳純文字,使用 Python 將文字整理成 WordPress HTML:

from bs4 import BeautifulSoup
import os

input_file = "article_raw.txt"
output_file = "article.html"

if os.path.exists(input_file):
    with open(input_file, "r", encoding="utf-8") as f:
        article_text = f.read()
    # 將每段換行包成 

paragraphs = [f"<p>{line.strip()}</p>" for line in article_text.split("\n") if line.strip()] formatted_content = "\n".join(paragraphs) with open(output_file, "w", encoding="utf-8") as f: f.write(formatted_content) print(f"{output_file} 生成完成") else: print(f"{input_file} 不存在,請先生成文章內容")

步驟三:WordPress 自動發佈文章

import requests
from requests.auth import HTTPBasicAuth

url = "https://你的網站網址/wp-json/wp/v2/posts"
username = "你的帳號"
app_password = "你的應用程式密碼"

try:
    with open("article.html", "r", encoding="utf-8") as f:
        content = f.read()
    data = {"title": "AI 自動生成文章測試", "content": content, "status": "publish"}
    response = requests.post(url, auth=HTTPBasicAuth(username, app_password), json=data)
    response.raise_for_status()
    print("發佈成功:", response.status_code)
except Exception as e:
    print("發佈錯誤:", e)

FAQ 常見問題

ChatGPT API 如何自動生成文章?

透過設定 prompt 生成文章,再轉換為 HTML 並使用 WordPress REST API 發佈。

WordPress 可以自動發佈 AI 文章嗎?

可以,透過 REST API 搭配應用程式密碼即可自動發佈。

需要會寫程式嗎?

基本需要,但按照教學可以完成整套流程。

文章生成後需要手動轉 HTML 嗎?

程式會自動轉換成 HTML 格式,確保 WordPress 可直接發佈。

常見錯誤如何排除?

依照每個步驟對照錯誤訊息,例如 ModuleNotFoundError、401、403、404 等,可快速修正。

適合新手操作嗎?

教學流程完整,步驟清楚,新手也能完成。

    PAGE TOP