Python WordPress XMLRPC提交WP Job Manager列表:分类与位置为空排查
问题排查与修复方案
你的代码里有两个关键问题导致分类和位置字段为空,咱们一步步来修正:
1. 职位分类(job_listing_category)的错误处理
WP Job Manager的职位分类是自定义分类法,不是自定义字段。你不能把它放到custom_fields里,而是需要通过terms属性来关联对应的分类术语。
首先你需要先确认目标分类术语的ID(或者通过名称获取ID),然后把它添加到widget.terms中:
# 先获取职位分类的术语(比如名称为"hotel"的分类) terms = wp.call(taxonomies.GetTerms('job_listing_category')) hotel_term = next(t for t in terms if t.name == 'hotel') # 关联到职位列表 widget.terms = [WordPressTerm({'id': hotel_term.id})]
2. 职位位置(job_location)的自定义字段格式错误
你现在的custom_fields写法不对,每个自定义字段应该是一个包含key和value键的字典,而不是把两个字段放到同一个字典里。正确的写法应该是:
widget.custom_fields = [ {'key': 'job_location', 'value': 'Newyork'}, # 如果还有其他自定义字段,继续添加 ]
完整修复后的代码
把上面的修正整合到你的代码里,最终版本应该是这样:
from wordpress_xmlrpc import Client, WordPressPost, WordPressTerm from wordpress_xmlrpc.methods.posts import NewPost from wordpress_xmlrpc.methods import taxonomies wp = Client('http://127.0.0.1/15wp/xmlrpc.php', 'admin', '123456') # 创建新职位列表 widget = WordPressPost() widget.post_type = 'job_listing' widget.title = 'Widgetlast02' widget.content = 'This is the widgets description.' widget.post_status = 'publish' # 处理职位分类:获取并关联"hotel"分类 terms = wp.call(taxonomies.GetTerms('job_listing_category')) try: hotel_term = next(t for t in terms if t.name == 'hotel') widget.terms = [WordPressTerm({'id': hotel_term.id})] except StopIteration: print("Error: 找不到名称为'hotel'的职位分类,请先在后台创建该分类") # 处理职位位置:设置自定义字段 widget.custom_fields = [ {'key': 'job_location', 'value': 'Newyork'} ] # 发布职位 widget.id = wp.call(NewPost(widget))
额外注意事项
- 确保你在WordPress后台已经创建了名称为
hotel的job_listing_category分类,否则代码里的StopIteration捕获会提示错误。 - 如果你的WP Job Manager还有其他必填字段(比如薪资、职位类型等),也需要按照对应的方式设置(自定义字段或分类)。
内容的提问来源于stack exchange,提问作者Kevin
相关产品推荐
相关产品推荐

