Skip to content

Instantly share code, notes, and snippets.

@luizbills
Created September 19, 2023 16:18
Show Gist options
  • Save luizbills/dda7e0c5fe3573acd6a2251e314bfad3 to your computer and use it in GitHub Desktop.
Save luizbills/dda7e0c5fe3573acd6a2251e314bfad3 to your computer and use it in GitHub Desktop.
Deletes product images when a WooCommerce product is permanently deleted
<?php
function lpb_purge_product_images ( $id ) {
if ( ! function_exists( 'wc_get_product' ) ) return; // prevent fatal errors
$product = wc_get_product( $id );
if ( ! $product ) return;
$image_id = $product->get_image_id();
if ( $image_id ) {
error_log( "Deleting product #{$id} main image..." );
wp_delete_attachment( $image_id, true );
}
$gallery = $product->get_gallery_image_ids();
if ( is_array( $gallery ) && count( $gallery ) > 0 ) {
error_log( "Deleting product #{$id} gallery images..." );
foreach ( $gallery as $image_id ) {
wp_delete_attachment( $image_id, true );
}
}
}
add_action( 'before_delete_post', 'lpb_purge_product_images' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment