👁️ 271
👍 97
📅 2026-06-13 收录
🔄 2026-06-13 更新

正文内容

使用 Gutenberg 的 WordPress API

概述

本技能提供全面指导,帮助您通过 WordPress REST API 创建和管理采用 Gutenberg 块编辑器格式的文章。内容涵盖身份认证、块序列化、媒体上传及发布工作流。

快速入门

在使用 API 前,请确保已具备以下条件:

  1. WordPress 站点:已启用 REST API(默认启用)
  2. 身份认证凭据

    • 应用密码(Application Password)(适用于 WordPress 5.6+):在 /wp-admin/admin.php?page=application-passwords 页面生成
    • JWT Authentication 插件(替代方案):需提前安装并配置
    • 基础认证(Basic Auth)的用户名/密码(不推荐用于生产环境)
  3. 基础 URLhttps://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 认证

若使用 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}"}

使用 Gutenberg 块创建文章

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 = '\n\n'.join(block_html)
    
    return {
        "title": title,
        "content": content,
        "status": "draft",  # 或 "publish"
        "format": "standard"
    }

常用块示例

详见 [references/common_blocks.md](references/common_blocks.md),其中包含以下块类型的详细示例:

  • 带格式化的段落块(Paragraph blocks)
  • 标题块(Heading blocks,h2–h4)
  • 带图注与对齐方式的图像块(Image blocks)
  • 列表块(有序/无序列表,List blocks)
  • 引用块(Quote blocks)
  • 代码块(Code blocks)
  • 自定义 HTML 块(Custom HTML blocks)
  • 栅格与布局块(Columns and layout blocks)

完整工作流

第一步:准备身份认证

将凭据设置为环境变量或存入配置文件。

第二步:构建文章数据

定义标题、内容块、分类(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']

特色图像(Featured Image)

# 先上传图片,再设为特色图像
image_data = upload_image("path/to/image.jpg")
post_data["featured_media"] = image_data['id']

自定义字段(ACF)

若使用 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 块 HTML
  • media_uploader.py:批量上传图片

参考资料

  • [common_blocks.md](references/common_blocks.md):各类块的详细使用示例
  • [api_reference.md](references/api_reference.md):完整的 WordPress REST API 官方参考文档
  • [troubleshooting.md](references/troubleshooting.md):常见问题与解决方案

资源文件

  • 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"
  }'