如何使用WordPress REST API来实现自动发布文章

“`html




使用 WordPress REST API 实现自动发布文章


使用 WordPress REST API 实现自动发布文章

1. 准备工作

  • WordPress 站点:确保已安装并启用 REST API(默认已启用)。
  • 认证方式:选择以下任一认证方式:
    • OAuth 2.0(推荐)
    • Basic Auth(需启用 WordPress 的 rest_authentication_key

2. 获取认证令牌(OAuth 2.0)

步骤

  1. 注册应用
  2. 获取 Access Token:使用 Client IDClient Secret 通过 OAuth 流获取令牌。

示例(curl)

curl -X POST https://your-site.com/wp-json/jwt-auth/v1/token \
     -H "Content-Type: application/json" \
     -d '{
         "client_id": "your-client-id",
         "client_secret": "your-client-secret",
         "grant_type": "client_credentials"
       }'

响应会包含 access_token

3. 构造请求体

发布文章需要提供以下字段(可选):

  • title(标题)
  • content(正文)
  • statuspublishdraft
  • categories(分类 ID 列表)
  • tags(标签 ID 列表)

示例请求体

{  
  "title": "自动发布的文章",  
  "content": "

这是通过 REST API 自动发布的文章内容。

", "status": "publish", "categories": [1], "tags": [2] }

4. 发送 POST 请求

使用 access_token 发送请求到 /wp-json/wp/v2/posts 端点。

示例(curl)

curl -X POST https://your-site.com/wp-json/wp/v2/posts \
     -H "Authorization: Bearer your-access-token" \
     -H "Content-Type: application/json" \
     -d '{
         "title": "自动发布的文章",  
         "content": "

这是通过 REST API 自动发布的文章内容。

", "status": "publish" }'

响应示例

{  
  "id": 123,  
  "date": "2023-10-05T12:34:56",  
  "title": {"rendered": "自动发布的文章"},  
  "excerpt": {"rendered": ". .."}  
}

5. 使用编程语言实现(Python 示例)

import requests

url = "https://your-site.com/wp-json/wp/v2/posts"
headers = {
    "Authorization": "Bearer your-access-token",
    "Content-Type": "application/json"
}
data = {
    "title": "Python 自动发布",
    "content": "

使用 Python 脚本自动发布文章。

", "status": "publish" } response = requests.post(url, headers=headers, json=data) print(response.json())

6. 常见问题与解决方案

问题 解决方案
认证失败 检查 access_token 是否有效,或切换为 Basic Auth。
请求体格式错误 确保 JSON 格式正确,字段名与 API 要求一致。
权限不足 确认用户角色有 edit_posts 权限,或使用管理员凭据。

7. 安全建议

  • 避免明文存储密钥:使用环境变量或加密存储 Client Secret
  • 限制 API 访问:通过 .htaccess 或插件限制 IP 访问。
  • 定期轮换令牌:避免长期使用单个令牌。

通过以上步骤,您可以实现自动发布文章的功能。根据实际需求选择认证方式,并确保数据安全性和格式正确性。



“`

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *