It is possible to bulk create products on WooCommerce? I am using the wp-cli Product command but it seems that I have to create one by one.
<?php
$products = array(
array('title' => 'My product 1'),
array('title' => 'My product 2'),
// ...
// 10.000 more products
);
foreach ($products as $product) {
$cliProduct = new WC_CLI_Product();
$cliProduct->create(array(), $product);
WP_CLI::success("Added Product #{$product['title']}");
}
This takes a lot of time since it is going to make a query for each product, even worse, it is going to be a cron job that will be run regularly. I also have to check if the product exist, in that case, update it instead of create a new product.
So the number of queries will be multiplied by 2.
Product Exists? Update it, else Create it
Is there a better way to do this? Maybe I should query the database directly, but it looks dirty.
Is there any WP function to query the database without having to create my own DB connection?
For WooCommerce Version 3.0 or above.
Assuming you have an array like this and you have Unique SKU to identify product.
$products = [
0 => [
'title' => 'My Simple product 1',
'sku' => 'sku1',
'category_ids' => [23,45]
//...
//...
],
1 => [
'title' => 'My Simple product 1',
'sku' => 'sku1'
//...
//...
]
];
Pass the above array through wh_myCustomProduct() method.
function wh_myCustomProduct($product_array)
{
if (!empty($product_array)):
foreach ($product_array as $product):
$product_id = wc_get_product_id_by_sku($product['sku']);
//no product exist with the given SKU so create one
if (empty($product_id)):
$product_id = wh_createOrUpdateProduct($product);
//product found
else:
$product_id = wh_createOrUpdateProduct($product,$product_id);
endif;
endforeach;
endif;
}
function wh_createOrUpdateProduct($product, $productId = 0){
$objProduct = new WC_Product($productId);
$objProduct->set_sku($product['id']); //Set product SKU.
$objProduct->set_name($product['title']); //Set product name.
$objProduct->set_description($product['description']); //Set product description.
$objProduct->set_description($product['price']); //Set product price.
$objProduct->set_category_ids($product['category_ids']); //Set product category ID.
$objProduct->set_stock_status('instock');
$objProduct->set_manage_stock(true); //Set true if you want WooCommerce to manage your stock
$objProduct->set_stock_quantity($product['rating']['count']); //Set product stock qty.
$objProduct->set_status('publish'); //Set product status
$productID = $objProduct->save(); //Saving the data to create new product, it will return product ID.
return $productID;
}
Hope this helps!
Reference:
Related:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With