最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

plugin development - How to only Load scripts on variable products page

programmeradmin1浏览0评论

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?

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?

Share Improve this question asked Jan 30, 2020 at 12:43 Younes.DYounes.D 1629 bronze badges 1
  • 1 Maybe something like this? – kero Commented Jan 30, 2020 at 13:35
Add a comment  | 

2 Answers 2

Reset to default 0

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/patrickgilmour/9d4a28b4a2f0c1dcecbf and here https://wordpress/support/topic/condition-to-check-if-product-is-simple-or-variable.

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"
发布评论

评论列表(0)

  1. 暂无评论