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

Solution 1:

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.

Solution 2:

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