'how to bulk remove all woocommerce products images gallery from host and site

I’ve just inherited a site that’s being migrated to a new host, and I’m attempting to tidy up the database during the process.

The WooCommerce site had roughly 100,000 products resulting in somewhere around 3,000,000 product images gallery.

how to erase all product images gallery attached to _product type posts, as well as wiping their records from the database.

End goal is to permanently delete all product images gallery from the media library as well as the database.

Any help would be much appreciated.



Solution 1:[1]

This is not tested and its recommended to create backup before this. Test it step by step with debug to know what is happening. Uncomment //if($attachment_ids): if you are happy with the results and run again to delete the images. Also before that i will recommend to remove any unneeded image sizes to optimize your image situation and then continue with this function.

function clear_product_gallery_images() {
    //For speed we need only product ids
    $args = array('return' => 'ids');
    
    //Get all ids
    $product_ids = wc_get_products($args);
    error_log(print_r($product_ids,true));
    //Collect all attachment ids
    $attachment_ids = array();

    foreach($product_ids as $pid) {
        //Get product object
        $product = new WC_product($pid);
        $image_ids = $product->get_gallery_image_ids();
        //Check image ids that we collect for each product
        error_log(print_r($image_ids,true));
        foreach($image_ids as $image_id):
            if(!in_array($image_id, $attachment_ids)):
                $attachment_ids[] =  $image_id;
            endif;
        endforeach;
    }
    //Check what kind of ids we have collected
    error_log(print_r($attachment_ids,true));
    //if($attachment_ids):
        //foreach($attachment_ids as $att_id):
            //Set to false if you want to move in trash
            //Set to true if you want to delete
            //wp_delete_attachment($att_id,false);
        //endforeach;
    //endif;
}
add_action( 'init', 'clear_product_gallery_images');

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1