Background:
I've come accross this WP issue: https://core.trac.wordpress.org/ticket/41445
In short: when you make a request to a post over the REST API, if the featured image was originally uploaded to a different post and this post is not accessible via the REST API (eg. the original post is trashed, is a draft, etc), you get a 403 error.
This is a bug in the WordPress API and it has not been fixed yet.
Apparently, this is happening because all attachments inherit the status from their parent post (in the database, post_status='inherit'
)
Possible Workarounds:
- Following this suggestion, I've updated the status of all the images I currently have in the DB:
UPDATE wp_posts
SET post_status='publish'
WHERE post_type = 'attachment'
AND post_mime_type LIKE 'image/%';
This fixes the issue for all the images I currently have... but it obviously doesn't fix any images that will be uploaded in the future.
- I can grant extra capabilities to my users.
In my case, it worked by adding edit_posts
, edit_private_posts
and edit_others_posts
.
Solves the problem but it's definitely not ideal...
Permanent Solution?
I wonder what's the best way to get a permanent fix for this. Maybe creating a hook with add_attachment and changing the status right after an image is uploaded to WP?
Am I missing something here? Is there a better approach?
UPDATE (june 2019)
As stated in the comments, @cjbj's answer does exactly what I was asking for (when a new attachment is uploaded, it sets the status of this attachment to 'publish'). Unfortunately, it seems that this solution will break the Media Library, as it does not display images/attachments with post_status='publish'.
For anyone facing this same issue, I recommend taking the route of adding extra capabilities to users.