Last active
August 27, 2023 14:01
-
-
Save shivapoudel/885bf74358ade6d207b6f1095903500a to your computer and use it in GitHub Desktop.
WooCommerce - Automatically delete attached images after product deletion
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Delete attached images after product deletion. | |
* | |
* @since 1.0.0 | |
* | |
* @see wp_delete_post() | |
* | |
* @param int $post_id Post ID. | |
*/ | |
function woocommerce_delete_product_images( $post_id ) { | |
// Check if empty trash is invalid. | |
if ( isset( $_GET['action'], $_GET['delete_all'] ) && -1 !== (int) $_GET['action'] ) { | |
return; | |
} | |
// Check if product delete action is invalid. | |
if ( isset( $_GET['action'], $_GET['post'] ) && 'delete' !== $_GET['action'] && $post_id === (int) $_GET['post'] ) { | |
return; | |
} | |
if ( class_exists( 'WooCommerce' ) ) { | |
$product = wc_get_product( $post_id ); | |
if ( $product ) { | |
$featured_image_id = $product->get_image_id(); | |
$gallery_image_ids = $product->get_gallery_image_ids(); | |
if ( ! empty( $featured_image_id ) ) { | |
if ( defined( 'WP_DEBUG' ) ) { | |
wc_get_logger()->info( sprintf( 'Featured image ID %d for product ID %d deleted successfully.', $featured_image_id, $product->get_id() ), ['source' => 'auto-delete-product-images'] ); | |
} | |
wp_delete_attachment( $featured_image_id, true ); | |
} | |
if ( ! empty( $gallery_image_ids ) ) { | |
if ( defined( 'WP_DEBUG' ) ) { | |
wc_get_logger()->info( sprintf( 'Gallery image IDs %s for product ID %d deleted successfully.', wc_print_r( $gallery_image_ids, true ), $product->get_id() ), ['source' => 'auto-delete-product-images'] ); | |
} | |
foreach( $gallery_image_ids as $gallery_image_id ) { | |
wp_delete_attachment( $gallery_image_id, true ); | |
} | |
} | |
} | |
} | |
} | |
add_action( 'before_delete_post', 'woocommerce_delete_product_images' ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment