通过 REST API 创建、编辑和发布 WordPress 文章,全面支持 Gutenberg 区块。当 Codex 需要自动化 WordPress 内容发布、生成…
WordPress API with Gutenberg.是一项面向实际任务的技能,主要用于Overview. 此技能为与WordPress REST API互动提供了全面的指导,以使用Gutenberg块编辑器格式创建和管理帖子. 它覆盖了。它将相关步骤、工具调用和结果整理方式集中到统一流程中,帮助使用者更快完成目标并减少重复操作。
实际使用前应先确认任务范围、数据来源、运行环境、必要权限和关键参数,再依据技能说明逐步执行;若输入条件不完整,应先补齐信息或采用保守配置,避免因错误假设导致结果偏离需求。
执行过程中需要关注工具调用是否成功、接口或依赖是否可用、输出格式是否符合预期,并对异常提示、缺失字段和边界情况进行处理;涉及批量任务时,还应保存进度,避免中断后重复操作。
本技能提供全面指导,帮助您通过 WordPress REST API 创建和管理采用 Gutenberg 区块编辑器格式的文章。内容涵盖身份验证、区块序列化、媒体上传及发布工作流。
使用 API 前,请确保已具备以下条件:
WordPress 站点:已启用 REST API(默认启用)
身份验证凭据:
/wp-admin/admin.php?page=application-passwords 页面生成基础 URL: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 插件,请先获取令牌:
import requests
wp_url = "https://your-site.com"
username = "admin"
password = "password"
# 获取令牌
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 字段应包含区块注释及 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 = '\n\n'.join(block_html)
return {
"title": title,
"content": content,
"status": "draft", # 或 "publish"
"format": "standard"
}
详见 references/common_blocks.md 中的详细示例,包括:
将凭据设置为环境变量或配置文件中。
定义标题、内容区块、分类、标签及特色图像。
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 插件:
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}")
常见问题:
scripts/ 目录包含以下辅助工具:
wp_publish.py:完整的发布流程脚本block_generator.py:从 Markdown 生成 Gutenberg 区块 HTMLmedia_uploader.py:批量上传图像common_blocks.md:详细的区块示例api_reference.md:完整的 WordPress REST API 参考文档troubleshooting.md:常见问题与解决方案templates/article_template.json:典型文章结构的 JSON 模板block_samples/:各类内容类型的示例区块 HTML# 使用 curl 配合 Application Password 发送请求
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"
}'
相关专题
热门下载
相关下载
精品课程
共6课时 | 54.6万人学习
共89课时 | 133.4万人学习
共49课时 | 82.2万人学习