Did I do it right? Deleting images after deleting product. Woocommerce

Looking at @obmerks answer on https://stackoverflow.com/questions/12997698/delete-images-after-post you can simplify it with this:

foreach ( $productIds as $productId ) {
  $child_atts = $wpdb->get_col("SELECT ID FROM {$wpdb->posts} WHERE post_parent = $productId AND post_type="attachment"");
  foreach ( $child_atts as $id ) wp_delete_attachment($id,true);
}

Note: as per documentation https://codex.wordpress.org/Function_Reference/wp_delete_attachment set the second parameter to true to force delete the attachment, otherwise it goes to trash.

Leave a Comment