Question

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?

Was it helpful?

Solution

Try this:

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

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

    if(!file_exists($file)){
        wp_delete_post( $img->ID, false );
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with wordpress.stackexchange
scroll top