I created this small script to create wordpres posts, using Basic Auth, and it works. The problem is when I try to assign multiple categories to a post.
The reference is pretty vague. It says that the categories
field must be an array. But it doesn't specify if it should be an array of category
objects or if the id
of these categories must be passed to the field.
https://developer.wordpress.org/rest-api/reference/posts/#schema-categories
So I tried to make it fail so I can get more info from an exception message. The exception message says something like categories[0] is not an integer
So I tried with a list of integers. And then, it works. But only one category is assigned, only the last category in the list.
So, How do I add more categories to a post ?
N1: Categories with id's 13
and 16
actually exists in my wordpress install.
N2: I know that I could create a draft, then create new requests to create categories then, use an update post endpoint to assign categories to posts... But in theory, should be possible to pass multiple categories just creating the post, since its in the reference xd
N3: I don't care about security. It is not a requirement.
import base64
import requests
r = requests.session()
wp_host = 'wphost.dev'
wp_username = 'FIXME'
wp_password = 'FIXME'
# BUILD BASIC AUTH STRING
basic_auth = str(
base64.b64encode('{user}:{passwd}'.format(
user=wp_username,
passwd=wp_password
).encode()
), 'utf-8')
# PARAMETERS TO POST REQUEST
p = {
'url': 'http://{wp_host}/wp-json/wp/v2/posts'.format(wp_host=wp_host),
'headers': {'Authorization': 'Basic {basic_auth}'.format(basic_auth=basic_auth)},
'data': {
'title': 'My title',
'content': 'My content',
'categories': [13, 16],
'status': 'publish',
},
}
# THE REQUEST ITSELF
r = r.post(url=p['url'], headers=p['headers'], data=p['data'])
# Output
print(r.content)
# ... "categories":[16],"tags":[] ...
base64
andrequests
these are python libraries, so you need to install python and then from command line usepip install <library_name>
– Parmenides