Remove duplicate attachments

function get_attachment_files(){
$args = array(
    'post_type' => 'attachment',
    'numberposts' => -1,
    'post_status' => null,
    'post_parent' => 0
);
$attachments = get_posts($args);
 if ($attachments) {
    foreach ($attachments as $post) {
        setup_postdata($post);
        wp_delete_post( $post->ID );
    }
 }
}
add_action('admin_init','get_attachment_files');

adapted from: http://wpsnipp.com/index.php/functions-php/list-all-unattached-files-in-media-library/

I’d be careful of this though, because I am not sure it won’t delete the images too. In fact, I think it will, but I am throwing it out there as fodder and not as a perfect solution.

If you dig into wp_delete_attachment there is a filter called wp_delete_file that you might be able to use to trick the function into deleting files from a made-up directory, ie not deleting your actual files, but I can’t be certain.

Leave a Comment