What’s the proper way to find and remove duplicate images from posts and the media library?

combining the two answer on this page, I found this worked.

$args = new WP_Query(array(
  'post_type' => 'post',
  'posts_per_page' => -1
));

$loop = new WP_Query($args);

while($loop->have_posts()) {
  the_post();
  $args2 = array(
    'order' => 'ASC',
    'post_type' => 'attachment',
    'post_parent' => $post->ID,
    'post_mime_type' => 'image');
    $attachments = get_posts($args2);
    if($attachments) {
      foreach ($attachments as $img_post) {
        if( ((strpos($img_post->guid, '1.jpg')!== false) || (strpos($img_post->guid, '1.gif')!== false) || (strpos($img_post->guid, '1.png')!== false))){
          $stuff = $img_post->guid;
          wp_delete_attachment($img_post->ID);
        } 
      }
    }
} wp_reset_postdata();

Leave a Comment