I want to be able to identify and delete media items that are attached to posts as featured images.
- Identify all featured image attachments
SELECT DISTINCT meta_value AS attachment_id FROM wp_postmeta WHERE meta_key = '_thumbnail_id';
This returns all attachment IDs used as featured images.
- See the actual media files
SELECT p.ID, p.post_title, p.guid FROM wp_posts p JOIN wp_postmeta pm ON pm.meta_value = p.ID WHERE pm.meta_key = '_thumbnail_id' AND p.post_type = 'attachment';
This returns the ID, Post Title and the Image file name and path.
- Delete the Attachments
DELETE p FROM wp_posts p JOIN wp_postmeta pm ON pm.meta_value = p.ID WHERE pm.meta_key = '_thumbnail_id' AND p.post_type = 'attachment'; Step 4 — Clean up the meta references
This will delete the attachment records.
- Delete the thumbnail meta rows
DELETE FROM wp_postmeta WHERE meta_key = '_thumbnail_id';
This will delete the id records and help keep the database tidy.
- Deleting the media files from disk
It is important to note that this process merely identifies and detaches the attachments which are featured images and deletes those records from the media library – it does not delete the media files from disk. If you wish to do this, copy the list of file names from step 2 and then either delete the files manually from disk or write a script to delete each one sequentially.
