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

0 views
0

I create, update and delete products using Woocommerce RestAPI, specifically this method:

$woocommerce->post('products/batch', $data);

After this method connected images remain in the server and db.

So, this is the code which deletes connected images from the database and server folder after deleting the post (product):

$this->woocommerce->post('products/batch', $data);
$this->deleteImages($data['delete']); // [ $key => $id_post ]

private function deleteImages($productIds)
    {
        foreach ( $productIds as $productId ) {
            $args = [
                //'numberposts' => 2,
                'order' => 'ASC',
                'post_mime_type' => 'image',
                'post_parent' => (int) $productId,
                'post_status' => 'inherit',
                'post_type' => 'attachment',
            ];
            $child = get_children($args);

            foreach ($child as $id => $item) {
                $pathImg = str_replace(get_site_url(), ABSPATH, $item->guid);
                $pathParts = pathinfo($pathImg);
                $extension =  end(explode(".", $pathImg));
                $imgWithoutExtension = $pathParts['dirname'] . '/' . basename($pathParts['basename'], '.' . $extension);

                array_map('unlink', glob($imgWithoutExtension . '*')); //ex:[img.jpg, img1x1.jpg, img5x5.jpg, img.gif]
                wp_delete_post($id);
            }
        }
    }

Is it normal realization? How would you edit this code?