WooCommerce Deleting Product and Automatically Delete Product Image and Gallery

When you add new product, content and also the add product image and to product gallery, if in case you want to delete the product, the product images assign to it will not delete a automatically.

If you want to delete the images (attachments ids) automatically with the product, you need to piece of code in your functions.php

delete will work if you finally delete the product on the Trash section or Empty Trash

add_action( 'before_delete_post', 'custom_delete_product_images_by_product', 10, 1 );

function custom_delete_product_images_by_product( $post_id ) {
	
	//get product id
	$product = wc_get_product( $post_id );

	//failsafe
	if ( ! $product ) {
		return;
	}

	//get images
	$featured_image_id  = $product->get_image_id();
	$image_galleries_id = $product->get_gallery_image_ids();

	//delete featured (check first if empty)s
	if ( ! empty( $featured_image_id ) ) {
		wp_delete_post( $featured_image_id );
	}

	//delete gallery/attachment (check first if empty)
	if ( ! empty( $image_galleries_id ) ) {
		foreach ( $image_galleries_id as $single_image_id ) {
			wp_delete_post( $single_image_id );
		}
	}
}