wc_get_product_id_by_sku() returns 0 for products added programatically via update_post_meta

wordpress.stackexchange https://wordpress.stackexchange.com/questions/385003

  •  19-05-2021
  •  | 
  •  

Question

I am parsing some products from XML and adding them into the database in woocommerce programmatically. SKU along with other data is saved with update_post_meta($post_id, '_sku', (string)$product->id); and is visible in the back-end. The problem is that when I try to check if there exists product with some SKU added this way programatically I always get 0.

wc_get_product_id_by_sku('SOMESKU');

The only way I will get real product ID is if I manually edit that product in the backend and save it.

Was it helpful?

Solution

The problem was that I didn't create product with WC_Product object. When I create product with this object it works.

for instance

$product = new WC_Product; 
$product->set_name("my product");
$product->set_sku("345678");
$product->save();

Then I can easity get the ID of the product by SKU

$post_id = wc_get_product_id_by_sku('345678');
Licensed under: CC-BY-SA with attribution
Not affiliated with wordpress.stackexchange
scroll top