FoamyMedia
FoamyMedia

Reputation: 496

Check product type is not working - woocommerce

I need an if else statement to check if a product is simple or variable on woocommerce so I can show the correct add to cart button for a custom product page.

div class="six">

<?php

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

<p>single</p>


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

<?php } ?>

</div>

However get this error message

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

Upvotes: 1

Views: 5653

Answers (1)

dipmala
dipmala

Reputation: 2011

Make sure you have global $product; before this code.

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

            <p>single</p>


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

            <?php } ?>

        </div>

Another way is below.

$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
}

Upvotes: 6

Related Questions