Attachment metadata has value of '1'
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:
- Has anyone else have encountered such issue with the attachment's meta and do you have any ideas why it's happening and maybe even how to fix this?
- Is there a good way for me to preserve my changes to the core files between WP version updates? For now I see the only way is to create a plugin that completely overrides core's `WP_REST_Attachments_Controller` class with its copy that has my patch but I feel that it will be a big trouble to maintain. Can I just override a function in a class before it's called? I'm not that savvy in internal workings of WP and not a PHP dev, so I'm seeking an advice on the best possible way to do this.
Topic core-modifications rest-api post-meta attachments media Wordpress
Category Web