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:
The result is always simple.
This sounds confusing, doesn’t it? I feel the same way.
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';
This is the right way to get the product type.
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.5 / 5. Vote count: 20