Woocommerce - how to tell if product post has variations or not

Variable product always is based on WC_Product_Variable class. E.g. WooCommerce Subscriptions follows this approach.

So, the checking can be:

is_a( $product, 'WC_Product_Variable' )

This ensures that the type of product is variable regardless of the presence of children. And it's fast.


After much heartache, I have found the following two solutions:

In the product loop, you can use this:

 if( $product->has_child() ) { 

but for some reason in the short description on the single product page, I had to use this:

global $post;
$children = get_pages('child_of='.$post->ID);
if( count( $children ) !== 0 ) {

Hope this helps others that were struggling as I was...


Use $product->is_type() function to check the product type. To check if the product is a variable product use:

global $product;

// $product->is_type( $type ) checks the product type, string/array $type ( 'simple', 'grouped', 'variable', 'external' ), returns boolean

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

There is also $product->get_type() function that returns the internal type of a product as a string.


For some reason if you have deleted your variation, the has_child() function it still turns true.

So I used the below solution

if(empty($product->get_available_variations())) {
  // Your code goes here
}

Tags:

Woocommerce