add_action( 'before_delete_post', 'delete_post_or_product_media', 10, 1 ); function delete_post_or_product_media( $post_id ) { // Check if the post is a WooCommerce product if ( 'product' === get_post_type( $post_id ) ) { $product = wc_get_product( $post_id ); if ( !$product ) { return; } // Get product featured image and gallery images $featured_image_id = $product->get_image_id(); $gallery_image_ids = $product->get_gallery_image_ids(); // Delete featured image if ( !empty( $featured_image_id ) ) { wp_delete_attachment( intval( $featured_image_id ), true ); } // Delete gallery images if ( !empty( $gallery_image_ids ) ) { foreach ( $gallery_image_ids as $image_id ) { wp_delete_attachment( intval( $image_id ), true ); } } } // Get all media attached to the post (non-product) $attached_media = get_attached_media( '', $post_id ); if ( !empty( $attached_media ) ) { foreach ( $attached_media as $media ) { // Make sure $media->ID is properly escaped and cast to an integer $attachment_id = intval( $media->ID ); if ( $attachment_id ) { wp_delete_attachment( $attachment_id, true ); } } } }

Showing 25–36 of 453 results

×
×