How To Get Product Type In WooCommerce

Contents

4.2
(42)

When developing plugins for WooCommerce, sometimes, knowing the product’s type is very important. The funny thing about WooCommerce is if you create a product from the class “WC_Product” and run:

$product->get_type();

The result is always simple.

This sounds confusing, doesn’t it? I feel the same way.

Get WooCommerce Product Type Using WC_Product_Factory

Since version 3.0, there is a convenient static method in WC_Product_Factory class that helps you get the type of product quickly:

WC_Product_Factory::get_product_type($product_id);

If the product is valid, you will get the product type as string (simple, variable…)

If the above method doesn’t work, let’s continue.

Getting product type using taxonomy

If you want the get_type method to return the correct type of the product, you need to create the product with the appropriate class. For example, for the get_type function to return ‘variable’, you need to create the product with the following syntax:

$product = new WC_Product_Variable($product_id);

However, how do you know what class to use when first creating the product?

The answer lies in the following code:

$terms = get_the_terms($this->product->get_id(), 'product_type');
$product_type = (!empty($terms)) ? sanitize_title(current($terms)->name) : 'simple';

As you can see from the code, it gets the taxonomy ‘product_type’ of the product and return the taxonomy name if exist, otherwise, it returns ‘simple’.

So, if you have the same problem, this is the code to use.

Click on a star to rate it!

Average rating 4.2 / 5. Vote count: 42

No votes so far! Be the first to rate this post.


2 thoughts on “How To Get Product Type In WooCommerce

  1. Hello for some reason your code always return “simple” on my end, even if the product is variable, does this work on certain woocommerce version? I use Woocommerce 3.x

Leave a Reply

Your email address will not be published. Required fields are marked *