Create Custom Menu in WordPress Dashboard
Complete tutorial on create custom menu in wordpress dashboard. Discover practical examples, implementation tips, and expert advice for WordPress and WooCo
Read More โAutomatically remove WooCommerce product featured images and gallery images when products are deleted using before_delete_post action hook and wp_delete_attachment function. Prevent orphaned media files, clean up server storage automatically, delete both featured image and gallery images, use wc_get_product to retrieve image IDs, implement proper deletion with wp_delete_attachment force parameter, and maintain clean media library without manual intervention for efficient WooCommerce store management.
By default, WooCommerce does not delete product images when you delete a product. However, this tutorial will guide you on setting up a custom function that removes the product's images along with the product itself.
Step 1: Create a Function to Delete Images Associated with a Product
Create a custom function that removes both the featured image and the gallery images linked to a product.
function auto_delete_product_images($post_id) {
$product = wc_get_product($post_id);
if ($product) {
$gallery_ids = $product->get_gallery_image_ids();
$featured_image_id = $product->get_image_id();
// Remove featured image
if ($featured_image_id) {
wp_delete_attachment($featured_image_id, true);
}
// Remove gallery images
foreach ($gallery_ids as $image_id) {
wp_delete_attachment($image_id, true);
}
}
}
Step 2: Attach the Function to Product Deletion
Use the before_delete_post action hook to attach the function to product deletion.
add_action('before_delete_post', 'auto_delete_product_images');
Step 3: Implement the Code in the Theme's functions.php File
Insert the code into your theme's functions.php file, ideally in a child theme to keep the functionality after future theme updates.
Step 4: Verify the Deletion of Product Images
After adding the function and hook, test the process. When you delete a product from WooCommerce, the related images should also be deleted from your server.
Important Notes:
External Resources:

Search our archives or reach out to our team for solutions and expert advice.