Skip to content

Instantly share code, notes, and snippets.

@jb510
Created March 29, 2022 02:43
Show Gist options
  • Save jb510/a4e44167bef2c7f89fb3765066601909 to your computer and use it in GitHub Desktop.
Save jb510/a4e44167bef2c7f89fb3765066601909 to your computer and use it in GitHub Desktop.
WooCommerce Delete Product Images with Product Deletion
<?php
/**
* WooCommerce Delete Product Images with Product Deletion
*
* @since 2.1.0
* @link https://gitlab.com/9seeds/plugins/9s-core-functionality
*
* @author Jon Brown <jb@9seeds.com>
* @copyright Copyright (c) 2022, Jon Brown
* @license http://opensource.org/licenses/gpl-2.0.php GNU Public License
*/
// Automatically Delete WooCommerce Images After Deleting a Product
add_action( 'before_delete_post', 's9_delete_product_images', 10, 1 );
function s9_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 );
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment