WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

Best way to programatically remove attachments that are missing images?

I ask because after using a caching plugin, I have images that have been input in the database as attachments that don't actually exist. These usually take the form of xxxx.1jpg, where xxxx.jpg is a valid. Sometimes this number is a 2 or a 21. bonus image attachment

I guess it would be better to just remove "duplicate" bad images. I think it might be good to have other types of missing images remain, so they could be corrected. Ideas?

share|improve this question
up vote 2 down vote accepted

Try this:

$imgs = get_posts("post_type=attachment&numberposts=-1");

foreach($imgs as $img){
    $file = get_attached_file($img->ID);

        wp_delete_post( $img->ID, false );
share|improve this answer
Thats a great PHP function to know, thanks! – two7s_clash May 9 '11 at 3:23

protected by Community May 17 at 13:25

Thank you for your interest in this question. Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).

Would you like to answer one of these unanswered questions instead?

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