upload featured image to wordpress via REST API

71 Views Asked by At

I try to create a new post at wordpress and upload with this featured image. I was created function that upload the image to wordpress media library:

import requests

file = "D:/myproject/tmp-images/" + filename
media = {'file': open(file,"rb")}
responce = requests.post(url + "wp-json/wp/v2/media", headers = header_json, files = media)
media_id = responce.json()["id"]
return media_id`

and after that I was created function that create new post with featured image param:

import requests
import json
import base64

media_id = <here i got media id from the previus function>

url = "https://XXX/wp-json/wp/v2/posts"
user = "XXX"
password = "XXX"

credentials = user + ':' + password
token = base64.b64encode(credentials.encode())
header = {'Authorization': 'Basic ' + token.decode('utf-8')}
post = {
    'title': 'title title title',
    'status': 'publish',
    "meta": {
        "location": "new york",
        "datetime": 1683846000,
        "url": "https://www.google.com",
        "affiliate-url": "https://www.google.com",
        "check-status": "not-checked",
        "approve-status": "not-approve",
        'featured_media': 150
    }
}
responce = requests.post(url, headers=header, json=post)
print(responce)

but its not working... I got status code of 201 but the featured image not define... how can I do that?

thanks

0

There are 0 best solutions below