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.