How to check if a given ID is for a product variation? woocoomerce

Viewed 3766

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??? enter image description here

4 Answers

You can get the product by using wc_get_product().

$product = wc_get_product($ID);

if( $product->is_type( 'simple' ) ){
    // simple product
} elseif( $product->is_type( 'variable' ) ){
   // variable product
}

This way you will always get the correct product class simple/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.

$product=wc_get_product($product_id);
$product_parent=$product->get_parent_id();

if($product_parent==0){
//what you want to do with non product that is not a variation
}else{
//what you want to do with product 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

If you feed the ID into get_post_type() it should return with either 'product' or 'product_variation'. This worked for me.

$post_type = get_post_type($ID);

if( $post_type == 'product' ){
    // product
} elseif( $post_type == 'product_variation' ){
   // product variation
}
Related