代码之家  ›  专栏  ›  技术社区  ›  FoamyMedia

检查产品类型是否无效-Woomerce

  •  -1
  • FoamyMedia  · 技术社区  · 6 年前

    我需要一个if-else语句来检查woomerce上的产品是简单的还是可变的,这样我就可以为自定义产品页面显示正确的add to cart按钮。

    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 回复  |  直到 6 年前
        1
  •  2
  •   dipmala    6 年前

    确保你有 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
    }