skip to Main Content

I’m trying to set notifications when I have products from these two different categories inside the card in WooCommerce.

This is the code which I using:

add_action( 'woocommerce_checkout_before_customer_details', 'webroom_check_if_product_category_is_in_cart' );
function webroom_check_if_product_category_is_in_cart() {

    $cat_in_cart = false;

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

        if ( has_term( 'cat1', 'product_cat', $cart_item['product_id'] ) &&
             has_term( 'cat2', 'product_cat', $cart_item['product_id'] ) ) {
            $cat_in_cart = true;
            break;
        }
    }

    if ( $cat_in_cart ) {
        $notice = 'Notification';
        wc_print_notice($notice, 'notice');
    }
}

This code works perfectly if I only set one category, but when I set two categories, for some reason I don’t have results nor errors.

2

Answers


  1. Chosen as BEST ANSWER

    Here is the solution:

    add_action( 'woocommerce_before_cart', 'webroom_check_if_product_category_is_in_cart' );
    function webroom_check_if_product_category_is_in_cart() {
    
        $cat1_in_cart = false;
        $cat2_in_cart = false;
    
        foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
    
            if ( has_term( 'cat1', 'product_cat', $cart_item['product_id'] ) ) {
                $cat1_in_cart = true;
            } elseif(has_term( 'cat2', 'product_cat', $cart_item['product_id'] )){
                $cat2_in_cart = true;
            }
        }
    
        if ($cat1_in_cart === true && $cat2_in_cart === true) {
            $notice = 'Notification';
            wc_print_notice($notice, 'notice');
        }
    }
    

  2. This should get you what you want. The problem is in your original function, is that you were checking each product if it had both categories.

    You need to split up the the conditions and then check the final conditions.

    add_action( 'woocommerce_checkout_before_customer_details', 'webroom_check_if_product_category_is_in_cart' );
    
    function webroom_check_if_product_category_is_in_cart() {
    
        $cat_one_in_cart = false;
        $cat_two_in_cart = false;
    
        foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
            if ( has_term( 'cat1', 'product_cat', $cart_item ) ) {
                $cat_one_in_cart = true;
                break;
            }
    
            if ( has_term( 'cat2', 'product_cat', $cart_item ) ) {
                $cat_two_in_cart = true;
                break;
            }
        }
    
        if ( $cat_one_in_cart && $cat_two_in_cart ) {
            $notice = 'Notification';
            wc_print_notice($notice, 'notice');
        }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search