5

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

  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?

3
  • 1
    Can you take a look at this search results and see if you find relevant information to add to the Question?
    – brasofilo
    Commented Jan 20, 2013 at 20:57
  • @brasofilo I checked the previous questions with Google. I didn't find anything which relates specifically to my problem.
    – Omar Abid
    Commented Jan 21, 2013 at 16:39
  • In the media library you can sort by the "Attached to" column. Can you not sort and then bulk delete all the un-attached items? Commented Jan 22, 2013 at 4:20

1 Answer 1

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.