I need a code to check wether a woocommerce product type is not "variable"
To check if something IS a variable product, I usually use this:
if ($product->is_type('variable') ) {
// do something
}
But I need to check if it is NOT a variable product, so I thought I was supposed to do it this way but this results in PHP errors…
if (! $product->is_type('variable') ) {
// do something
}
EDIT: I get the following error: "Fatal error: Uncaught Error: Call to a member function is_type() on null"
I thought there was something wrong with my code. But then I tested it in other template files and it worked. I wanted to use my php codition in functions.php to dequeue a style everywhere except for variable products. Like so:
global $product;
if (! $product->is_type('variable') ) {
wp_dequeue_style('sample');
}
So it can not be done this way? Any idea?
3
Answers
Your theme’s functions.php file gets called for every page on your WP site. If you have a weak controlled function there you are veri likely going to face some fatal error all over the website. In your case all you need to do is to check if $product is indeed an instance of Wc_Product or null.
So, change your code into this:
The explanation is that we check that $product actually has a value and it is really a Wc_Product class instance. If that is ok then you check for the $product->is_type. This way you won’t face fatal errors all over when you’r global $product variable has not been set yet by Woocommerce
To avoid this error, you can try the following lightweight way:
Or also this heavier way:
How about this?