I have an array full of produtcs SKU’s that i search for the ID.
$ID = wc_get_product_id_by_sku($CodProduto);
then i initialize the object and set the stock for the current amount.
$Product = new WC_Product( $ID);
$return = wc_update_product_stock( $Product, $Stock);
So far so good! All works fine. My problem is when the $ID
is for a product variation it wont initialize the object and will give an error. So i initialize all ID’s with:
$Product = new WC_Product_Variation( $ID );
And then i update the stock like i did before.
The problem is that when a product DONT have variation, the woocommerce puts the Name as (no title) but the stock works fine.
Is there a way to check if the ID is for a variation without initialize the object $Product???
4
Answers
You can get the product by using wc_get_product().
This way you will always get the correct product class simple/variation.
I think you can use another method by searching in database
For example, if not sure whether this ID is for Product or Variation Product, you can use:
( get_post( not_sure_ID ) )->post_parent;
As a child post (Variation Product) , its parent value will not be 0. On the other hand is 0 (Product).
or
( get_post( not_sure_ID ) )->post_type;
If this ID is for Variation Product, return value should be product_variation
You can check if product is variation with get_parent_id(), if it is a variation you will get the parent id, if not you will get zero. i.e.
If you feed the ID into get_post_type() it should return with either ‘product’ or ‘product_variation’. This worked for me.