1

I'm currently migrating data from a custom CMS over to WooCommerce. I'm able to create the products fine using the following code:

try {
    $product = new WC_Product_Variable();
    $product->set_name($productData["Name"]);
    $product->set_description($productData["Description"]);
    $product->set_price($productData["Price"]);
    $product->set_sku("PW" . $productData["ID"]);
    $product->set_category_ids($productData["NewCategoryIds"]);
    $product->set_status($productData["OnlineStatus"]);

...

The problem I'm having though is that when I re-run my script, I get WC_Data_Exception: Invalid or duplicated SKU.

This is odd, because when looking at the save function within the WC_Product_Variable class, the comment says:

Save data (either create or update depending on if we are working on an existing product).

... but the save function within that class doesn't appear to do any updating.

aynber
  • 22,380
  • 8
  • 50
  • 63
Liam McArthur
  • 1,033
  • 3
  • 18
  • 42
  • By default SKU is unique per product in Woocommerce, You have either to disable SKU for products or allow duplicate SKU, see this [answer](https://stackoverflow.com/a/41585021/5638658) for more information. – Shahin Jan 12 '19 at 17:15
  • I need the SKU keeping. I just want to be able to update a product if it already exists, otherwise - create it. – Liam McArthur Jan 12 '19 at 17:37
  • 1
    Try to use the function `wc_get_product_id_by_sku($sku)` to check if the product exist then update it or create a new one if not – Shahin Jan 12 '19 at 17:52

0 Answers0