简体   繁体   中英

Adding multiple products programmatically in WooCommerce

I'm trying to programmatically bulk add products in WooCommerce but for some reason, it's only adding the first product. I am making a request to an app that returns a JSON response with product names and descriptions. So far my code looks like what I have below:

    $curl_connection = curl_init($url);
    curl_setopt($curl_connection, CURLOPT_CONNECTTIMEOUT, 30);
    curl_setopt($curl_connection, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl_connection, CURLOPT_SSL_VERIFYPEER, false);
    
    $data = json_decode(curl_exec($curl_connection), true);
    curl_close($curl_connection);
    
    foreach($data['data'] as $media){

        $objProduct = new WC_Product();
        $objProduct->set_name($media['name']);
        $objProduct->set_status("publish");  
        $objProduct->set_catalog_visibility('visible');
        $objProduct->set_description($media['description']);
        $objProduct->set_sku("product-sku"); 
        $objProduct->set_price(10.55); 
        $objProduct->set_regular_price(10.55); 
        $objProduct->set_manage_stock(true);
        $objProduct->set_stock_quantity(10);
        $objProduct->set_stock_status('instock'); 
        $objProduct->set_backorders('no');
        $objProduct->set_reviews_allowed(true);
        $objProduct->set_sold_individually(false);
        $objProduct->set_category_ids(array(1,2,3)); 

        $product_id = $objProduct->save();
    }

I got it. You cannot create a product with a duplicate SKU.

$objProduct->set_sku("product-sku");

The code above needs to have a unique string for all products.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM