检查产品类型不起作用 - woocommerce

时间:2018-06-12 10:51:19

标签: wordpress woocommerce

我需要if else语句来检查产品在woocommerce上是否简单或可变,以便我可以为自定义产品页面显示正确的“添加到购物车”按钮。

div class="six">

<?php

if( $product->is_type( 'simple' ) ){ ?>

<p>single</p>


<?php } elseif( $product->is_type( 'variable' ) ){ ?>
<p>variable</p>

<?php } ?>

</div>

但是收到此错误消息

Fatal error: Uncaught Error: Call to a member function is_type() on string in /Applications/MAMP/htdocs/jollybrewer/wp-content/plugins/woocommerce/templates/content-single-product.php:48 Stack trace: #0 /Applications/MAMP/htdocs/jollybrewer/wp-includes/template.php(690): require() #1 /Applications/MAMP/htdocs/jollybrewer/wp-content/plugins/woocommerce/includes/wc-core-functions.php(180): load_template('/Applications/M...', false) #2 /Applications/MAMP/htdocs/jollybrewer/wp-content/themes/jolly/woocommerce/single-product.php(41): wc_get_template_part('content', 'single-product') #3 /Applications/MAMP/htdocs/jollybrewer/wp-includes/template-loader.php(74): include('/Applications/M...') #4 /Applications/MAMP/htdocs/jollybrewer/wp-blog-header.php(19): require_once('/Applications/M...') #5 /Applications/MAMP/htdocs/jollybrewer/index.php(17): require('/Applications/M...') #6 {main} thrown in /Applications/MAMP/htdocs/jollybrewer/wp-content/plugins/woocommerce/templates/content-single-product.php on line 48

1 个答案:

答案 0 :(得分:1)

请确保在此代码之前有global $product;

            <?php
            global $product;
            if( $product->is_type( 'simple' ) ){ ?>

            <p>single</p>


            <?php } elseif( $product->is_type( 'variable' ) ){ ?>
            <p>variable</p>

            <?php } ?>

        </div>

另一种方式如下。

$product_id = 12; // the ID of the product to check
$_product = wc_get_product( $product_id );
if( $_product->is_type( 'simple' ) ) {
  // do stuff for simple products
 } else {
   // do stuff for everything else
}