You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Python调用WordPress REST API创建文章时多分类多标签失效问题

问题原因与解决方案

你的代码存在问题,并非WordPress的bug。问题出在请求的编码方式上:

当你使用requests.post的data参数传递包含列表的字典时,requests会将其编码为表单数据(application/x-www-form-urlencoded)。对于categories: [32,30,33]这类列表参数,表单数据会被编码成categories=32&categories=30&categories=33,而WordPress REST API在处理这种表单数据时,只会保留最后一个传入的ID(也就是33),标签同理只保留最后一个109。

修复代码

将请求中的data=data替换为json=data,requests会自动将字典序列化为JSON格式,并设置正确的Content-Type: application/json请求头,这样WordPress就能正确解析数组类型的参数了:

import requests
import json

# URL and auth
wp_url = "http://FQDN/wp-json/wp/v2/posts"
auth = ("MyUser", "MyPassword")


# Post params
data = {
  "categories": [32, 30, 33],
  "tags": [121, 95, 117, 109],
  "title": "This is the Title",
  "content": "Content Lorem Ipsum",
  "status": "publish",
}

# Post - 使用json参数替代data
wp_create_response = requests.post(wp_url, auth=auth, json=data)

# Check if successfull
if wp_create_response.status_code == 201:
  post_id = wp_create_response.json()["id"]
  post_tagids = wp_create_response.json()["tags"]
  post_categoryids = wp_create_response.json()["categories"]

  print(f"Successfully created Post! ID: {post_id}")
  print(f"Post Tag IDs: {post_tagids}")
  print(f"Post Category IDs: {post_categoryids}")

else:
  print("Error: " + wp_create_response.text)

验证结果

修改后,创建的文章会正确关联所有传入的分类和标签ID,输出的Post Tag IDs和Post Category IDs会显示完整的列表。


内容的提问来源于stack exchange,提问作者Keschbert

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 09:40:24