I recently used an image importer that has duplicated all the images. They are attached to the right posts and the posts are fine (not duplicated).
How do I run through my media library deleting duplicate images?
I know its too late for this answer, but can help others, you can use Media Deduper plugin to index and find duplicated image , it is also good enough to link the post to existing image.
You can use custom script which you need to add to your functions.php file of your theme or plugin.
function delete_duplicate_images_from_website() {
global $wpdb;
// Get all attachment IDs from website
$attachments = $wpdb->get_results("SELECT ID FROM {$wpdb->posts} WHERE post_type = 'attachment' AND post_mime_type LIKE 'image/%'", ARRAY_A);
$hashes = array();
$duplicates = array();
foreach ($attachments as $attachment) {
$attachment_id = $attachment['ID'];
$file_path = get_attached_file($attachment_id);
if (file_exists($file_path)) {
$file_hash = md5_file($file_path);
if (isset($hashes[$file_hash])) {
// If duplicate found, then store ID for deletion
$duplicates[] = $attachment_id;
} else {
// Store the hash
$hashes[$file_hash] = $attachment_id;
}
}
}
// Delete duplicates attachements
foreach ($duplicates as $duplicate_id) {
wp_delete_attachment($duplicate_id, true);
}
echo 'Duplicate Attachment deleted: ' . count($duplicates);}
You can run this function manually delete_duplicate_images_from_website();
on localhost to test if this works for you.
The best way (if the duplicated images are the ones attached) is to order by date, and bulk delete all the older ones.