Remove duplicate attachments

Here is the situation:
I have an automated script that upload attachments and link each attachment to a specific post. By mistake, the script run multiple times and I have the following

  1. More than one attachment post in the Media library for a single file (the different attachment posts have the same File URL).

    Read More
  2. One of these attachment is actually attached to the post.

What I want to do is obviously is clean up the media library. I need to remove the attachment post without removing the file, and also make sure that I don’t remove the ones that are actually attached to their posts.

Any ideas?

Related posts

Leave a Reply

1 comment

  1. 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.