为什么要用 REST API 自动发文
WordPress 自带的后台编辑器写文章没问题,但如果你需要批量发布、定时采集、或者用 AI 自动生成内容,手动在后台一篇篇写就不现实了。WordPress 内置的 REST API 可以让你通过代码创建、编辑、删除文章,实现全自动化。
适合场景:
- AI 自动生成文章并发布到 WordPress
- 从其他平台批量迁移文章
- 定时采集和发布特定主题的内容
- 多站点统一管理发布
第一步:创建应用程序密码
REST API 认证需要用户名+应用程序密码(不是你的 WordPress 登录密码)。
- 登录 WordPress 后台
- 进入「用户」→「个人资料」
- 拉到底部找到「应用程序密码」部分
- 输入一个名称(如 “API发布”),点「添加新的应用程序密码」
- 复制生成的密码(格式类似
xxxx xxxx xxxx xxxx xxxx xxxx)
重要:这个密码只显示一次,马上复制保存好。
第二步:测试 API 连接
用 curl 测试你的 WordPress REST API 是否正常:
# 测试 API 是否可达
curl https://yourdomain.com/wp-json/wp/v2/
# 测试认证是否成功
curl -u "用户名:应用程序密码" https://yourdomain.com/wp-json/wp/v2/users/me
如果第二个命令返回你的用户信息(ID、用户名等),说明认证成功。
第三步:获取分类 ID
发布文章需要指定分类 ID:
curl -u "用户名:密码" https://yourdomain.com/wp-json/wp/v2/categories?per_page=100
返回 JSON 数组,每个分类有 id 和 name。记下你需要的分类 ID。
如果分类不存在,可以创建:
curl -u "用户名:密码" -X POST https://yourdomain.com/wp-json/wp/v2/categories -H "Content-Type: application/json" -d '{"name":"AI教程","slug":"ai-tutorial"}'
第四步:发布文章
用 curl 发布
curl -u "用户名:应用程序密码" -X POST https://yourdomain.com/wp-json/wp/v2/posts -H "Content-Type: application/json" -d '{
"title": "测试文章标题",
"content": "<h2>这是正文</h2><p>这是一篇通过 REST API 发布的测试文章。</p>",
"status": "publish",
"categories": [3],
"excerpt": "这是文章摘要"
}'
参数说明:
title:文章标题content:文章正文,支持 HTMLstatus:publish直接发布,draft存为草稿categories:分类 ID 数组excerpt:文章摘要
用 Python 发布
import requests
import base64
SITE = 'https://yourdomain.com'
USER = 'your_username'
APP_PASSWORD = 'xxxx xxxx xxxx xxxx xxxx xxxx'
auth = base64.b64encode(f"{USER}:{APP_PASSWORD}".encode()).decode()
headers = {
"Authorization": f"Basic {auth}",
"Content-Type": "application/json"
}
data = {
"title": "Python 自动发文测试",
"content": "<h2>正文标题</h2><p>这是正文内容。</p>",
"status": "publish",
"categories": [3],
"excerpt": "文章摘要"
}
resp = requests.post(f"{SITE}/wp-json/wp/v2/posts", headers=headers, json=data)
result = resp.json()
print(f"发布成功!文章ID: {result['id']}")
print(f"文章链接: {result['link']}")
第五步:上传图片和设置特色图
上传图片到媒体库
import requests
import base64
# 上传本地图片
with open('image.jpg', 'rb') as f:
image_data = f.read()
upload_headers = {
"Authorization": f"Basic {auth}",
"Content-Disposition": 'attachment; filename="article-image.jpg"',
"Content-Type": "image/jpeg"
}
resp = requests.post(
f"{SITE}/wp-json/wp/v2/media",
headers=upload_headers,
data=image_data
)
media_id = resp.json()['id']
print(f"图片上传成功,媒体ID: {media_id}")
设置特色图片
发布文章时加上 featured_media 字段:
data = {
"title": "带特色图的文章",
"content": "<p>正文内容</p>",
"status": "publish",
"featured_media": media_id, # 上面上传得到的媒体ID
"categories": [3]
}
resp = requests.post(f"{SITE}/wp-json/wp/v2/posts", headers=headers, json=data)
第六步:设置 SEO 元数据(Yoast SEO)
如果你的 WordPress 装了 Yoast SEO,可以通过 REST API 设置 SEO 字段:
data = {
"title": "SEO 优化的文章",
"content": "<p>正文内容</p>",
"status": "publish",
"categories": [3],
"meta": {
"_yoast_wpseo_title": "自定义SEO标题 - 网站名",
"_yoast_wpseo_metadesc": "这是文章的 meta description,搜索引擎会显示这段文字。",
"_yoast_wpseo_focuskw": "目标关键词"
}
}
注意:不是所有 Yoast 版本都支持通过 REST API 写入 meta 字段。如果不生效,可以试试 Yoast 的 REST API 扩展插件。
第七步:完整自动化脚本示例
以下是一个完整的自动发文脚本框架:
import requests
import base64
import json
import time
class WordPressPublisher:
def __init__(self, site, username, app_password):
self.site = site.rstrip('/')
auth = base64.b64encode(f"{username}:{app_password}".encode()).decode()
self.headers = {
"Authorization": f"Basic {auth}",
"Content-Type": "application/json"
}
def get_categories(self):
resp = requests.get(
f"{self.site}/wp-json/wp/v2/categories?per_page=100",
headers=self.headers
)
return {c['name']: c['id'] for c in resp.json()}
def upload_image(self, image_path):
with open(image_path, 'rb') as f:
data = f.read()
h = {**self.headers, "Content-Disposition": f'attachment; filename="{image_path}"'}
resp = requests.post(
f"{self.site}/wp-json/wp/v2/media",
headers=h, data=data
)
return resp.json()['id']
def publish_post(self, title, content, category_id, excerpt="",
featured_media_id=None, status="publish"):
payload = {
"title": title,
"content": content,
"status": status,
"categories": [category_id],
"excerpt": excerpt
}
if featured_media_id:
payload["featured_media"] = featured_media_id
resp = requests.post(
f"{self.site}/wp-json/wp/v2/posts",
headers=self.headers, json=payload
)
return resp.json()
def update_post(self, post_id, **kwargs):
resp = requests.post(
f"{self.site}/wp-json/wp/v2/posts/{post_id}",
headers=self.headers, json=kwargs
)
return resp.json()
# 使用示例
wp = WordPressPublisher('https://yourdomain.com', 'user', 'app-password')
# 获取分类
cats = wp.get_categories()
print(f"可用分类: {cats}")
# 上传图片
img_id = wp.upload_image('/path/to/image.jpg')
# 发布文章
result = wp.publish_post(
title="自动发布的文章",
content="<h2>正文</h2><p>内容</p>",
category_id=cats['AI教程'],
excerpt="文章摘要",
featured_media_id=img_id
)
print(f"发布成功: {result['link']}")
常见问题
Q1:返回 401 Unauthorized
- 检查用户名是否正确(WordPress 用户名,不是邮箱)
- 检查应用程序密码是否正确(有空格分隔)
- 确认 REST API 没有被禁用(有些安全插件会关闭 REST API)
- 检查服务器是否配了 Basic Auth(如 Nginx 的 auth_basic),会冲突
Q2:返回 403 Forbidden / REST API 被禁用
- 检查是否安装了 Disable REST API 之类的插件
- 在 functions.php 或 mu-plugins 中确保没有禁用 REST API 的代码
Q3:中文标题乱码
- 确保请求头包含
Content-Type: application/json; charset=utf-8 - 用 Python requests 库时,
json=参数会自动处理编码
Q4:文章发布成功但前台看不到
- 检查
status是不是publish(不是draft或pending) - 检查分类是否存在
- 清除缓存(如果有缓存插件)
Q5:大批量发布被限流
- 每次请求间隔 1-2 秒:
time.sleep(2) - 使用草稿模式先批量创建,再统一修改为发布状态
- 检查是否有安全插件限流(如 Wordfence)
小结
WordPress REST API 自动发文的核心步骤:创建应用程序密码 → 测试连接 → 上传图片 → 发布文章。配合 Python 脚本和定时任务,可以实现全自动的内容发布流程。
来源:
© 版权声明
THE END
















暂无评论内容