Advertisement
Aurangajeb

Delete Associated Images When a Product Is Deleted Permanently

Dec 7th, 2021
968
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 0.65 KB | None | 0 0
  1. // Automatically Delete Woocommerce Images After Deleting a Product
  2. add_action( 'before_delete_post', 'delete_product_images', 10, 1 );
  3.  
  4. function delete_product_images( $post_id )
  5. {
  6.     $product = wc_get_product( $post_id );
  7.  
  8.     if ( !$product ) {
  9.         return;
  10.     }
  11.  
  12.     $featured_image_id = $product->get_image_id();
  13.     $image_galleries_id = $product->get_gallery_image_ids();
  14.  
  15.     if( !empty( $featured_image_id ) ) {
  16.         wp_delete_post( $featured_image_id );
  17.     }
  18.  
  19.     if( !empty( $image_galleries_id ) ) {
  20.         foreach( $image_galleries_id as $single_image_id ) {
  21.             wp_delete_post( $single_image_id );
  22.         }
  23.     }
  24. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement