Home > Net >  Stop adding different type of product to cart and show notice
Stop adding different type of product to cart and show notice

Time:08-16

I am trying to add different product in cart. There are two type of product one is other and another is simple.

I need to grab if simple product in the cart then only simple can added and other in cart then only other.

I don't want to add simple and other type of product simultaneously.

add_action('woocommerce_add_to_cart', 'custome_add_to_cart', 10, 6);
function custome_add_to_cart($cart_id, $product_id, $request_quantity, $variation_id, $variation, $cart_item_data) {
    global $woocommerce;
    //print_r($cart_item_data); //Current
    // die();

    //check if product already in cart
    if ( sizeof( WC()->cart->get_cart() ) > 0 ) {
        foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
            $product_type =  $cart_item['type'];
            if ($product_type == 'other'){
                if($cart_item_data['type'] == 'other'){
                    WC()->cart->add_to_cart( $product_id );
                    // print_r($cart_item); //Old Cart
                    // die();
                }else{
                    wc_print_notice( 'This type of product not added 1', 'notice' );
                }
            }else{

                //print_r($cart_item); //Old Cart
                if($cart_item_data['type'] != 'other'){
                    WC()->cart->add_to_cart( $product_id );
                }else{
                    wc_print_notice( 'This type of product not added 2', 'notice' );
                    exit;
                }
            }
        }
    }
}

I am using this hook but it's not working for me. It show 503 error.

CodePudding user response:

Instead of using woocommerce_add_to_cart use woocommerce_add_to_cart_validation This filter returns $passed, $product_id, $quantity, $variation_id, $variations but we need only the type of product.

add_filter( 'woocommerce_add_to_cart_validation', 'woocommerce_add_to_cart_validationcustom', 10, 2 );
function woocommerce_add_to_cart_validationcustom( $passed, $product_id ) {

    global $woocommerce;
    if(WC()->cart->is_empty()) return true;

    foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
        $product = $cart_item['data'];
        $current_type = $product->get_type();
    }
    //Get the product we are adding as object
    $product_to_add = wc_get_product( $product_id );
    $type_to_add = $product_to_add->get_type();
    
    // Check if the product type is the same
    if ( $current_type !== $type_to_add){
     wc_add_notice( sprintf( __( "This is my custom error", "your-theme-language" ) ) ,'error' );  
      return false;
    } else {
        return true;
    }
}
  • Related