Publish a post using XML-RPC WordPress API and Python with category

categories, python, wordpress, xml-rpc

Solution

XML-RPC WordPress API Document says:

struct terms: Taxonomy names as keys, array of term IDs as values.
struct terms_names: Taxonomy names as keys, array of term names as values.

This means terms and terms_names are directory, the key name is the name of taxonomy you want, and the value is an array list.

If you want to set a category, you should set

‘terms‘:{‘my-category’:[4]} 

or

‘terms_names’:{‘my-category’:["Wordpress"]} 

in the post structure, where "my-category" is the name of your taxonomy.

Some information from:解决Python发布wordpress内容返回抱歉,文章类型不支持您的分类法.错误

Problem

I'm doing a migration from a website to another one which use Wordpress. I created new custom types for my needs (with the plugin Custom Post Types), and I created categories for each custom type. I then wrote down a script in Python (adapted from this article), which gets the posts from the db and pushes them remotely on the new (testing) website, using the new Wordpress XML-RPC API supported since version 3.4.x. At the moment I can publish a new post with the correct post type. But if I specify a category, wordpress always returns me this error: ``` xmlrpclib.Fault: <Fault 401: 'Sorry, one of the given taxonomies is not supported by the post type.'> ``` I'm sure that the post type is supported by the given taxonomy. I think I'm using a wrong syntax to specify the category id. Here's the code: ``` import datetime, xmlrpclib, MySQLdb def post_remotely(post_data): wp_url = "[my wordpress blog url]" wp_username = "[myuser]" wp_password = "[mypasswd]" wp_blogid = "0" status = 'publish' server = xmlrpclib.ServerProxy(wp_url) data = { 'post_title': post_data['title'], 'post_content': post_data['content'], 'post_date': post_data['data'], 'post_type': post_data['post_type'], 'terms': post_data['categories'], 'post_status': status } post_id = server.wp.newPost(wp_blogid, wp_username, wp_password, data) return post_id ``` And on the caller, to specify the category: ``` new_post['categories'] = [ { 'term_id': 3, 'taxonomy': 'news-cat' } ] ``` "news-cat" is the name of the taxonomy associated to the custom type "news". "term-id" is the id of the category, which I found out using phpMyAdmin. I've also tried other approaches but to no avail. Without the category it works nicely. Thanks in advance for any help :)

Original source