使用Python Requests调用WordPress REST API分配分类失败排查
问题解决:WordPress API指定分类失败的原因及修复
你代码里有两个关键错误:
- 键名拼写错误:你写的
"categories:"多了个末尾的冒号,WordPress API识别不到这个字段,自然不会应用指定的分类,直接 fallback 到未分类。正确的键名是"categories"。 - 表单编码下的数组参数格式错误:因为你用的是
application/x-www-form-urlencoded格式提交数据,传递数组类型的参数(比如分类ID列表)需要用categories[]作为键名,而不是直接写categories。
修正后的代码如下:
# Post creator function def create_post(inputTitleSent, outputText): randomAuthor = random.choice(authorList) post_status = "draft" headers = { "Content-Type": "application/x-www-form-urlencoded" } post = { "title": inputTitleSent, "content": outputText, "status": post_status, "author": randomAuthor, "categories[]": 6 # 修正键名,用categories[]传递分类ID } url = wp_base_url + "/wp-json/wp/v2/posts" response = requests.post(url, data=post, headers=headers, auth=(wp_username,wp_password)) return response
另外补充一种更直观的方案:如果你改用JSON格式提交数据,就可以直接用"categories": [6]的写法,只需要修改请求头和数据处理方式:
# Post creator function def create_post(inputTitleSent, outputText): randomAuthor = random.choice(authorList) post_status = "draft" headers = { "Content-Type": "application/json" # 改成JSON格式 } post = { "title": inputTitleSent, "content": outputText, "status": post_status, "author": randomAuthor, "categories": [6] # 直接传列表格式 } url = wp_base_url + "/wp-json/wp/v2/posts" response = requests.post(url, json=post, headers=headers, auth=(wp_username,wp_password)) # 用json参数自动序列化 return response
内容的提问来源于stack exchange,提问作者overdeveloping
相关产品推荐
相关产品推荐

