PHP Woocommerce Delete All Products in CSV File

This script allows you to delete all file in csv file.

It uses SimpleCSV library in github : https://github.com/shuchkin/simplecsv


include __DIR__ . "/simplecsv-master/src/SimpleCSV.php";
include __DIR__ . "/../../wp-load.php";

#delete woocommerce products from csv with all images
$csv_products = SimpleCSV::import(__DIR__ . "/data.csv");
foreach ($csv_products as $csv_product) {
    $product_sku = $csv_product[0];
    $product_id = wc_get_product_id_by_sku($product_sku);

    if(!$product_id){
        continue;
    }

    $variation_sku = $csv_product[1];

    #delete product variations
    $product_variations = new WP_Query(array(
        'post_type' => 'product_variation',
        'post_status' => array('publish', 'pending', 'draft', 'auto-draft', 'future', 'private', 'inherit', 'trash'),
        'meta_query' => array(
            array(
                'key' => '_sku',
                'value' => $variation_sku,
                'compare' => '='
            )
        )
    ));

    if ($product_variations->have_posts()) {
        while ($product_variations->have_posts()) {
            $product_variations->the_post();
            wp_delete_post(get_the_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_id . "<br>";
    }



}

Leave a Reply

Your email address will not be published.