Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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?

share|improve this question
1  
Can you take a look at this search results and see if you find relevant information to add to the Question? –  brasofilo Jan 20 '13 at 20:57
    
@brasofilo I checked the previous questions with Google. I didn't find anything which relates specifically to my problem. –  Omar Abid Jan 21 '13 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? –  helgatheviking Jan 22 '13 at 4:20

1 Answer 1

up vote 1 down vote accepted
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.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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