skip to Main Content

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


  1. 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:

    global $product;    
    if (!empty($product) && is_a($product,Wc_Product::class) && ! $product->is_type('variable') ) {
        wp_dequeue_style('sample');
    }
    

    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

    Login or Signup to reply.
  2. To avoid this error, you can try the following lightweight way:

    if ( is_product() && ! has_term( 'variable', 'product_type', get_the_id() ) ) {
        wp_dequeue_style('sample');
    }
    

    Or also this heavier way:

    if ( is_product() ) {
        global $product;
        
        if ( ! is_a($product, 'WC_Product') ) {
            $product = wc_get_product( get_the_id() );
        }
        
        if ( is_a($product, 'WC_Product') && ! $product->is_type('variable') ) {
            wp_dequeue_style('sample');
        }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search