I’m uploading an image to wordpress and trying to attach it to a post. The code works, the guides I’ve found online:
- https://www.reddit.com/r/learnpython/comments/143okri/python_to_automate_featured_image_selection_for/
- https://developer.wordpress.org/rest-api/reference/posts/
They say i’m doing it correctly. Whats weird is the post request to update the post returns 200. however in the content returned featured_media is 0 instead of the value I set.
returned content from the post, you can see the featured media was 0
enter image description here
you can see here the payload has the field wordpress expects with a valid id
enter image description here
here is the code getting the featured_media id form the content dictionary I pass in and making the post to the post id.
endpoint = f'{WORDPRESS_SITE}/wp-json/wp/v2/news/{article_id}'
I know this endpoint is correct because I’m also updating the title, the content of this post above where I try to update the image. Originally I put them together but that wasn’t working so I tried just the media as a separate post. That didn’t work either.
if content.get('featured_media'):
data = {
"featured_media": content.get('featured_media')
}
response = requests.post(endpoint, json=data, headers=headers)
if response.ok:
logger.logger.info(f"featured image post was successful. {response.status_code}, {content.get('featured_media')}, endpoint: {endpoint}")
According to the docs this is the way you do it.
enter image description here
Really not sure what i’m doing wrong here. I see featured image is blank in the metadata in the returned content but no status or message as to why the image didn’t get set.
You can also see its not set on the article here.
enter image description here
- I’ve tried passing the _embeded metadata that exist on other posts that already have featured images.
- I’ve tried including the featured_media id in the combine data payload that I’m updating content and title in.
- I’ve tried multiple itterations from GPT.
- I’ve looked at docs and posts and seems I’m doing the right thing.
- Its just not working.
Grant Zukel is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.