While accessing /wp-json/wp/v2/media
endpoint I'd got an error 500. Checking the logs, I'd seen the following issue:
PHP Recoverable fatal error: Object of class stdClass could not be converted to string in /Applications/MAMP/htdocs/reinvently.local/wp-includes/rest-api/endpoints/class-wp-rest-attachments-controller.php
Basically, the error was caused by prepare_item_for_response
function in class-wp-rest-attachments-controller.php
because, for some reason, most of the attachments (>1k) had a string 1
as a value for _wp_attachment_metadata
key in the database. Which is, I suppose, is not a valid value at all.
I've tried to change all those values to NULL
(which removed the error) and use Fix Media Library plugin to restore metadata, but it again restored all the '1's.
I can't find the reason why it happens, since none of the installed plugins should cause that. All the attachments work as they should on the website, it's only the API that has errors. And the new files I upload have a correct object as metadata value, so again, no ideas why it happened to previous ones.
For now I've dealt with the error by monkey-patching class-wp-rest-attachments-controller.php
with a modified empty condition in prepare_item_for_response
:
// Ensure empty details is an empty object.
if ( empty( $data['media_details']) || is_string($data['media_details']) ) {
That is not an ideal way by any means, but it gets the job done, media files are accessible via REST API now.
I've done some research on the Net and haven't found the same error happened to anyone else. So now I have two questions: