If you’re experiencing broken images in the WordPress backend, you may want to check if they’re missing their post_mime_type information in the wp_posts table.
We recently worked on a project that was experiencing some strange behavior when it came to some of the site’s images:
- While images were appearing on the frontend, if you edited the page, the custom field that controlled that same image appeared unset (and even more concerning, if you then updated the page, the image was then lost on the frontend)
- Despite the edit screen not showing these custom fields as set, looking at the wp_postmeta table, the images were appropriately set in the database
- These same images had entries in the Media Library, however, their thumbnails were broken and if you tried to regenerate their thumbnails, an error would be thrown
Upon further investigation we discovered the wp_post table entries for these images were missing their post_mime_type data. A MIME type is a label used to identify a type of data and without this information certain parts of WordPress doesn’t know how to handle the file.
In addition to the entry in the wp_post table, each image holds information about its different thumbnail sizes in a _wp_attachment_metadata field in the wp_postmeta table. We found that this field was also missing information about these images’ MIME types.
That sounds like my thing! How do I fix it?
To fix this issue, you just need to add the MIME type to the image’s post_mime_type field in the wp_post table. Once you’ve done this, you can regenerate the image’s thumbnails and this will take care of the missing MIME type information in the wp_postmeta table.
You can add this info manually in the database, or you can programmatically loop through your images and assign them in bulk. If you do this, make sure to backup your database and website beforehand! With that said, here are a couple WordPress PHP functions that can help you out:
- get_attached_file() – This will return the image’s file path given its post ID
- wp_get_image_mime() – This will return the MIME type for an image given its file path
Putting it all together you can update an image’s post_mime_type data with the following code:
$image_url = get_attached_file($image_id); if ($mimetype = wp_get_image_mime($image_url)) { global $wpdb; $wpdb->update('wp_posts', array('post_mime_type'=>$mimetype),array('ID'=>$image_id)); }
Once that’s complete, regenerate the image’s thumbnails and it should be all fixed up!
Let us know below if you have any questions or need assistance with your project!