In this article, I'll demonstrate how to have Woocommerce photos automatically deleted if a product is deleted. By doing this, you can free up server space and lessen media library chaos. One word of caution, though: Should a product be deleted that had an image assigned to it, the picture will also be lost for the remaining products.
- Paste this code snippet inside your theme’s functions.php file or better yet, use the Code Snippets plugin for it.
// Automatically Delete Woocommerce Product 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 );
}
}
}
0 Comments