Remove product image when deleting product WooCommerce

Viewed 127

I'm deleting all of my out of stock products automatically with an sql statement (I saw the example at another question here on StackOverFlow). This deletes the product from the database but leaves the image in the media library. Is there a way to delete the image aswell?

Code:

function remove_out_of_stock_status(){   
   global $wpdb;

    $results = $wpdb->get_results( "
    DELETE p FROM {$wpdb->prefix}posts p 
    join {$wpdb->prefix}postmeta pm 
    on p.ID = pm.post_id 
    WHERE p.post_type = 'product' 
    and pm.meta_key = '_stock_status' 
    and pm.meta_value = 'outofstock'
" );
  }
  add_action( 'init', 'remove_out_of_stock_status', 10, 1 );
1 Answers

You can use before_delete_post hook to delete product image, If product get permanently deleted.

add_action('before_delete_post', 'delete_thumbnail_before_delete_post');
function delete_thumbnail_before_delete_post($post_id) {
    $post = get_post($post_id);
    if ($post->post_type === 'product') {
        $thumb_id = get_post_thumbnail_id($post_id);
        if ($thumb_id) {
            wp_delete_attachment($thumb_id, true);
        }
    }
}

Above code work fine for me!

Related