Search code examples
wordpresswoocommerceproductcart

replace existing product in cart when adding new but excluding specific products. Those specific product will be added and not gonna replaced


replace existing product in cart when adding new but excluding specific products. Those specific product will be added and not gonna replaced. My code:

add_filter( 'woocommerce_add_cart_item_data', 'woo_custom_add_to_cart' );

function woo_custom_add_to_cart($cart_item_data) {
    
     
        
     $product_categories = array('mid-career-package-deal','advanced-career-package-deal');
    $excluded_ids = array(1105,1108);
    
    if(! in_array( $product_categories,$excluded_ids ) ) {
         WC()->cart->add_to_cart();;
    }
        global $woocommerce;
        $woocommerce->cart->empty_cart();
    

    

    // Do nothing with the data and return
    return $cart_item_data;
 }

Solution

  • add_filter( 'woocommerce_add_to_cart_validation', 
     'remove_cart_item_before_add_to_cart', 20, 3 );
     function remove_cart_item_before_add_to_cart( $passed, $product_id, 
     $quantity ) 
     {
      $excluded_ids = array(1105, 1108);
      if( ! WC()->cart->is_empty()&& ! in_array( $product_id, $excluded_ids 
      ))
       WC()->cart->empty_cart();
      return $passed;
      }