Wopdpress AI Blogger

通过REST API实现WordPress文章的自动化创建与发布,支持Gutenberg区块格式。

已扫描
适合谁
内容运营人员、技术型博主或开发者
不适合谁
无WordPress站点的用户、不熟悉API操作的初学者
国内可用性
需网络配置。可能需要网络配置或第三方服务可访问。
安装难度
新手友好(★☆☆)。基于终端操作、依赖、API Key 和本地环境要求的初步判断。

安装与下载

openclaw skills install @chirukinbb/wordpress-api-gutenberg

Skill 说明

命令、参数、文件名以原文为准

WordPress API 与 Gutenberg

概述

本技能提供与 WordPress REST API 交互的全面指南,用于以 Gutenberg 块编辑器格式创建和管理文章。涵盖认证、块序列化、媒体上传及发布工作流。

快速开始

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

  1. WordPress 网站,且 REST API 已启用(默认开启)
  2. 认证凭证

- 应用密码(WordPress 5.6+):在 /wp-admin/admin.php?page=application-passwords 生成

- JWT 认证插件已安装(替代方案)

- 基本认证使用的用户名/密码(不推荐用于生产环境)

  1. 基础 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 插件,需先获取令牌:

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

使用 Gutenberg 块创建文章

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'<!-- wp:{block_name} {attrs_json} -->'
        block_html.append(f'{block_comment}{inner_html}<!-- /wp:{block_name} -->')

    content = '\n\n'.join(block_html)

    return {
        "title": title,
        "content": content,
        "status": "draft",  # 或 "publish"
        "format": "standard"
    }

常见块示例

详见 [references/common_blocks.md](references/common_blocks.md),包含以下示例:

  • 带样式的段落块
  • 标题块(h2-h4)
  • 带说明和对齐的图片块
  • 列表块(有序/无序)
  • 引用块
  • 代码块
  • 自定义 HTML 块
  • 列和布局块

完整工作流程

步骤 1:准备认证

通过环境变量或配置文件设置凭证。

步骤 2:创建文章数据

定义标题、内容块、分类、标签、特色图像等信息。

步骤 3:上传媒体(如需)

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()

步骤 4:创建文章

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()

步骤 5:更新状态

将草稿状态改为发布:

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']

自定义字段(ACF)

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

常见问题:

  • 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": "<!-- wp:paragraph --><p>你好世界!</p><!-- /wp:paragraph -->",
    "status": "draft"
  }'
C
@chirukinbb

已收录 1 个 Skill

相关推荐