Skip to content

Instantly share code, notes, and snippets.

@tallesairan
Created August 15, 2018 19:52
Show Gist options
  • Save tallesairan/25adfcf2d24f697253360a4bd4c44d71 to your computer and use it in GitHub Desktop.
Save tallesairan/25adfcf2d24f697253360a4bd4c44d71 to your computer and use it in GitHub Desktop.
Find duplicated attachment titles in wordpress and remove
<?php
$duplicate_titles = $wpdb->get_col("SELECT post_title FROM {$wpdb->posts} WHERE post_type = 'attachment' GROUP BY post_title HAVING COUNT(*) > 1");
echo "Find ".count($duplicate_titles)." duplicated titles \n";
foreach( $duplicate_titles as $title ) {
echo "find images with ".$title." \n";
$post_ids = $wpdb->get_col( $wpdb->prepare( "SELECT ID FROM {$wpdb->posts} WHERE post_type = 'attachment' and post_title=%s", $title ) );
// Iterate over the second ID with this post title till the last
foreach( array_slice( $post_ids, 1 ) as $post_id ) {
$status = (wp_delete_attachment( $post_id,1 )) ? 'Deleted' : 'Not deleted';
echo "Deleting media ".$post_id." ".$status." \n";
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment