Woocommerce when deleting a product, automatically also delete the product gallery and product image
woocommerce, wordpress
Solution
Although this is an old question, I will leave it here in case someone will be looking for it in the future.
Since you want to delete product images, you may try these neat and handy woocommerce functions to get attachments ids.
Something like this:
add_action( 'before_delete_post', 'delete_product_images', 10, 1 );
function 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 );
}
}
}
Works fine for me.
Problem
I was trying the following: when a product page gets deleted (permanently), it should also delete the: product gallery and product image which are attached to the post. I tried the solution i found on: https://wordpress.stackexchange.com/questions/109793/delete-associated-media-upon-page-deletion But it didn't work out for me.