1
votes

Please forgive me in advance if this is a stupid question.

So, I'm currently doing a check on all the items in the WooCommerce Cart.

If there's a product in the cart is in the category 'Practice' and there are no products in the cart with the category 'Qualifying', I want to show Message 1

If both 'Practice' and 'Qualifying' categories are in the cart, I want to show message 2.

Right now, here's my code:

<?php 
   $category_checks = array();

   // check each cart item for our category

   foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {

      $product = $cart_item['data'];
      $practice = false;
      $qualifying = false;

      if( has_term( 'practice', 'product_cat', $product->id ) && ! has_term( 'qualifying', 'product_cat', $product->id ) ) : ?>

         <?php $practice = true; ?>

         Upsell goes here (Message 1)

      <?php elseif( has_term( 'practice', 'product_cat', $product->id ) && has_term( 'qualifying', 'product_cat', $product->id ) ) : ?>

         <?php $qualifying = true; ?>

         No need to upsell (Message 2)

       <?php endif; ?>

<?php      

array_push( $category_checks, $practice, $qualifying );
 }

 if ( ! in_array( false, $category_checks, true ) ) {

 }
 ?>

I have two products that have one category each, one has 'Practice' category and one has 'Qualifying' category.

When I add these two products to the cart and try this code, I constantly get Message 1, even though I'm saying if it doesn't (!) have the term 'qualifying'.

What am I doing wrong here?

1

1 Answers

2
votes

Updated

There is some mistakes and errors in your code (For example in your code $product->id need to be now $product->get_id() or $cart_items['data']->get_id() since Woocommerce 3).

When using has_term() for cart items always use $cart_item['product_id'] for the product ID argument, but never $cart_item['data']->get_id() as it will not work on cart items that are product variations.
Woocommerce Product variations don't handle any custom taxonomy as Product categories or Product tagsā€¦

I have revisited your code. Try the following instead:

<?php 
    $taxonomy   = 'product_cat';
    $practice   = false;
    $qualifying = false;

    // Loop through order items
    foreach ( WC()->cart->get_cart() as $cart_item ) {
        $product_id = $cart_item['product_id'];

        if( has_term( 'practice', $taxonomy, $product_id ) )
            $practice = true;
        if( has_term( 'qualifying', $taxonomy, $product_id ) )  
            $qualifying = true;
    }

    if ( $practice && ! $qualifying )
        echo '<p>Upsell goes here (Message 1)</p>';
    elseif ( $practice && $qualifying )
        echo '<p>No need to upsell (Message 2)</p>';
?>  

It should better work as intended.