In this video I’m going to show you how to automatically delete Woocommerce images after deleting product. This way you free up server space and reduce media library clutter. One Warning though: If an image is assigned to more than one product then the other product will also lose this image after product deletion.
Paste this code snippet inside your theme’s functions.php file or better yet, use the Code Snippets plugin for it.
// Automatically Delete Woocommerce Images After Deleting a Product
add_action( 'before_delete_post', 'delete_product_images', 10, 1 );
function delete_product_images( $post_id )
{
$product = wc_get_product( $post_id );
if ( !$product ) {
return;
}
$featured_image_id = $product->get_image_id();
$image_galleries_id = $product->get_gallery_image_ids();
if( !empty( $featured_image_id ) ) {
wp_delete_post( $featured_image_id );
}
if( !empty( $image_galleries_id ) ) {
foreach( $image_galleries_id as $single_image_id ) {
wp_delete_post( $single_image_id );
}
}
}