skip to Main Content

I have a situation where user cannot add more than 1 product to cart from specific category. I tried using woocommerce_add_to_cart_validation filter hook.

This code works for all items and keep in cart last added item:

// before add to cart, only allow 1 item in a cart
add_filter( 'woocommerce_add_to_cart_validation', 'woo_custom_add_to_cart_before' );

function woo_custom_add_to_cart_before( $cart_item_data ) {
    global $woocommerce;
    
    $woocommerce->cart->empty_cart();
    
    // Do nothing with the data and return
    return true;
}

This code doesn’t work:

add_filter( 'woocommerce_add_to_cart_validation', 'woo_custom_add_to_cart_before' );

function woo_custom_add_to_cart_before( $cart_item_data ) {
    if( is_product_category( 'test' ) ) {
        global $woocommerce;
        $woocommerce->cart->empty_cart();

        // Do nothing with the data and return
        return true;
    }
}

Any help please?

2

Answers


  1. Chosen as BEST ANSWER
    function custom_maybe_empty_cart( $valid, $product_id, $quantity ) {
    
    foreach ( WC()->cart->get_cart() as $cart_item ){
        if( has_term( 'test', 'product_cat', $cart_item['product_id'] ) ) {
      if( ! empty ( WC()->cart->get_cart() ) && $valid ){
        WC()->cart->empty_cart();
        wc_add_notice( 'Only allowed 1 item in cart.', 'error' );
      }
    }
     }
     return $valid;
      }
    add_filter( 'woocommerce_add_to_cart_validation', 'custom_maybe_empty_cart', 10, 3 );
    

    This code worked for me pls. Thank you so much for helping everyone.


  2. Try this.

    add_action( 'woocommerce_before_calculate_totals', 'only_allow_one_item_from_specific_category', 10, 1 );
    function only_allow_one_item_from_specific_category( $cart ){
        foreach ( $cart->get_cart() as $cart_item_key => $cart_item ){
            if( has_term( 'test', 'product_cat', $cart_item['product_id'] ) ) {
                $cart->remove_cart_item( $cart_item['product_id'] );
            }
        }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search