
Presale One-pass Orchestrator
运行或监督单遍 Codex 实现,包含预检门控、分步计划执行及严格的 QA 缺陷闭环。适用于执行已批准的售前...
本技能提供全面指导,帮助您通过 WordPress REST API 创建和管理采用 Gutenberg 块编辑器格式的文章。内容涵盖身份认证、块序列化、媒体上传及发布工作流。
在使用 API 前,请确保已具备以下条件:
身份认证凭据:
/wp-admin/admin.php?page=application-passwords 页面生成https://your-site.com/wp-json/wp/v2
# 设置环境变量 export WP_URL="https://your-site.com" export WP_USERNAME="admin" export WP_APPLICATION_PASSWORD="xxxx xxxx xxxx xxxx xxxx xxxx"
import requests
import os
wp_url = os.environ.get('WP_URL')
username = os.environ.get('WP_USERNAME')
password = os.environ.get('WP_APPLICATION_PASSWORD')
auth = (username, password)
若使用 JWT 插件,需先获取访问令牌(token):
import requests
wp_url = "https://your-site.com"
username = "admin"
password = "password"
# 获取 token
resp = requests.post(f"{wp_url}/wp-json/jwt-auth/v1/token",
json={"username": username, "password": password})
token = resp.json()['token']
headers = {"Authorization": f"Bearer {token}"}
WordPress REST API 要求文章内容以 Gutenberg 序列化块格式提交。content 字段应包含块注释(block comments)与 HTML 内容。
def create_gutenberg_post(title, content_blocks):
"""
使用 Gutenberg 块创建文章。
参数:
title: 文章标题
content_blocks: 块字典列表,每个字典含 'blockName' 和 'attrs' 键
返回:
用于 POST 请求的 JSON 数据
"""
# 将块序列化为 Gutenberg 格式
block_html = []
for block in content_blocks:
block_name = block.get('blockName', 'core/paragraph')
attrs = block.get('attrs', {})
inner_html = block.get('innerHTML', '')
# 构建块注释
attrs_json = json.dumps(attrs) if attrs else ''
block_comment = f''
block_html.append(f'{block_comment}{inner_html}')
content = 'nn'.join(block_html)
return {
"title": title,
"content": content,
"status": "draft", # 或 "publish"
"format": "standard"
}
详见 [references/common_blocks.md](references/common_blocks.md),其中包含以下块类型的详细示例:
将凭据设置为环境变量或存入配置文件。
定义标题、内容块、分类(categories)、标签(tags)、特色图像(featured image)等字段。
def upload_image(image_path, post_id=None):
"""将图片上传至 WordPress 媒体库。"""
with open(image_path, 'rb') as f:
files = {'file': f}
data = {}
if post_id:
data['post'] = post_id
response = requests.post(f"{wp_url}/wp-json/wp/v2/media",
files=files, data=data, auth=auth)
return response.json()
def create_post(post_data):
"""创建新的 WordPress 文章。"""
response = requests.post(f"{wp_url}/wp-json/wp/v2/posts",
json=post_data, auth=auth)
return response.json()
将草稿更改为已发布状态:
def publish_post(post_id):
"""发布一篇草稿文章。"""
response = requests.post(f"{wp_url}/wp-json/wp/v2/posts/{post_id}",
json={"status": "publish"}, auth=auth)
return response.json()
# 获取或创建分类
def ensure_category(name, slug=None):
categories = requests.get(f"{wp_url}/wp-json/wp/v2/categories",
params={"search": name}, auth=auth).json()
if categories:
return categories[0]['id']
else:
new_cat = requests.post(f"{wp_url}/wp-json/wp/v2/categories",
json={"name": name, "slug": slug or name.lower()},
auth=auth).json()
return new_cat['id']
# 先上传图片,再设为特色图像
image_data = upload_image("path/to/image.jpg")
post_data["featured_media"] = image_data['id']
若使用 Advanced Custom Fields(ACF)插件:
post_data["meta"] = {
"your_field_name": "field_value"
}
始终检查响应状态:
response = requests.post(...)
if response.status_code in [200, 201]:
print("成功!")
else:
print(f"错误 {response.status_code}: {response.text}")
常见错误码说明:
401:身份认证失败403:用户权限不足404:接口未找到(请确认 WordPress 版本是否支持该端点)500:服务器内部错误(请检查 PHP 错误日志)scripts/ 目录中包含以下辅助工具脚本:
wp_publish.py:完整的文章发布流程脚本block_generator.py:从 Markdown 自动生成 Gutenberg 块 HTMLmedia_uploader.py:批量上传图片templates/article_template.json:典型文章结构的 JSON 模板block_samples/:各类内容类型对应的块 HTML 示例# 使用 curl + 应用密码发送请求
curl -X POST https://your-site.com/wp-json/wp/v2/posts
-u "admin:xxxx xxxx xxxx xxxx xxxx xxxx"
-H "Content-Type: application/json"
-d '{
"title": "我的新文章",
"content": "Hello World!",
"status": "draft"
}'
|
1 |
|







