How to create a new wordpress post with tags and meta data via REST API?

Viewed 443

I'm using the following code to automaticly create posts:

# coding: utf-8
import base64
import json
import requests
from pprint import pprint


def main():
    # Init
    url = "http://localhost/wp-json/wp/v2/posts"
    username = "admin"
    password = "password"
    credentials = "{}:{}".format(username, password)
    token = base64.b64encode(credentials.encode())

    # Header
    headers = {
        "user-agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36",
        "Authorization": "Basic {}".format(token.decode("utf-8")),
        "content-type": "application/json",
    }

    # Post info
    post = {
        "title": "This is a REST API test",
        "content": "This is a REST API <h1>test</h1>",
        "status": "publish",
        "categories":['2'],
        "tags":[],
        "meta":[]
    }

    # Post
    r = requests.post(
        url,
        headers=headers,
        json=post,
    )

    # Print
    pprint(r.text)


if __name__ == "__main__":
    main()

I tried couple of ways to add the metadata:

"meta":[
    {
        'key': 'Color',
        'value':  'Green'
    }, 
    {
        'key': 'Size',
        'value':  'S'
    }
]

And

"meta":[{
        'Color': 'Green',
        'Size':  'S'
}]

none of those methods seem to work, and the "Custom Fields" section in the edit post remains empty while the result that I'm looking for is to see data there

enter image description here

What am I doeing wrong? and how to fix it?

0 Answers
Related