Skip to content
Advertisement

WooCommerce Product SKU checking is not working

I am trying to create and update woocommerce products automatically from an API. I have created the starting point of the plugin and this is my method that gets the products from the external API and then loops through them and creates a simple product in woocoommerce.

It creates the products perfectly fine however if I run the code twice, the products do not get an update but a whole new batch of them are created (SKU are duplicated without any errors), it seems like the SKU is not recognized even though it exists and I can see it on the product’s dashboard and on the frontend here is my code so far:

JavaScript

does anyone have any ideas why the SKUs are present but not recognized and the products just keep duplicating? thanks.

Advertisement

Answer

Short answer will be if you just replace if( !$product_id ) by this if (empty($product_id )) it will solve the issue.

But a proper and working answer will be as you are creating a product in WooCommer then I will recommend using the WooCommerce native CRUD method. I know you have taken reference from my very old answer (I will update that answer shortly) at that time WooCommer do have an inbuilt method for creating products so we have to use WP methods.

Here is the working code sample.

JavaScript

working code example

Please Note: I have tested individual methods/functions but I haven’t tested the whole flow. Secondly, I haven’t handled the image part in the above code example, which I believe you will be able to handle easily.

Hope this helps!

Reference:

  • This is the WooCommerce official doc
  • You can also refer to this article where I have explained in detail how to use Product CRUD
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement