PHP Woocommerce Delete Products With Variations and images

Delete products with all information

<?php


include __DIR__ . "/../../wp-load.php";

#delete woocommerce products from array with all images
$products = [1,2,3]; // product id's
foreach ($products as $product) {

    $product_sku = $product;
    $product_id = wc_get_product_id_by_sku($product_sku);

    if(!$product_id){
        echo "Product with SKU: " . $product_sku . " not found.<br>\n";
        continue;
    }

    #delete product variations by product id
    $variations = get_children(array(
        'post_parent' => $product_id,
        'post_type' => 'product_variation',
        'fields' => 'ids'
    ));

    foreach ($variations as $variation_id) {
        wp_delete_post($variation_id, true);
    }

    #delete product images
    $product_images = get_post_meta($product_id, '_product_image_gallery', true);
    if($product_images){
        $product_image_gallery = explode(',', $product_images);
        foreach ($product_image_gallery as $image_id) {
            wp_delete_attachment($image_id, true);
        }
    }

    #delete product
    if ($product_id) {
        wp_delete_post($product_id, true);
        echo "Product deleted: " . $product_sku . " " . $product_id . "<br>\n";
    }

}

Leave a Reply

Your email address will not be published.