I'm looking for a way to load my JavaScript and CSS only on the product page, but only if it's a Variable Products.

The is_product() function works well, but my scripts are loaded for all types of products: Simple, Variable, Grouped .....

How to limit the loading of scripts only for a variable product?


WooCommerce conditional to test if a Product is Variable.

global $product
if( $product->is_type( 'variable' ) ){

  // a variable product


Found it here: https://gist.github.com/patrickgilmour/9d4a28b4a2f0c1dcecbf and here https://wordpress.org/support/topic/condition-to-check-if-product-is-simple-or-variable.

  • Hi , this solution return always simple . we must use wc_get_product instead of WC_Product class – Younes.D Jan 30 at 15:12

I have already tried this solutions :

$the_product = new WC_Product(get_the_ID());
$the_product->get_type();  // Return always "simple" 

So, I followed the documentation of the code Class WC_Product():

 * Get the product if ID is passed, otherwise the product is new and empty.
 * This class should NOT be instantiated, but the wc_get_product() function
 * should be used. It is possible, but the wc_get_product() is preferred.
 * @param int|WC_Product|object $product Product to init.

Now I get the correct product type with this:

    $the_product = wc_get_product( get_the_ID() );
    var_dump( $the_product->get_type() );

The output is correct :

string(8) "variable"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.