2
votes

What Woocommerce Does is...

When products are Sold Individually, and when the product already exists in the Cart and customer clicks on Add to Cart, Woocommerce shows Error Message "You cannot add another to your cart.....View Cart"

Instead of the above flow I want..

When customer clicks on Add to Cart and if the product already exists in the Cart then woocommerce should redirect to Checkout page straightway.

I think this can be achieved by editing few lines of code in class-wc-cart.php of Woocommerce Plugin.

The is given below:

// Force quantity to 1 if sold individually and check for existing item in cart
                if ( $product_data->is_sold_individually() ) {
                    $quantity         = apply_filters( 'woocommerce_add_to_cart_sold_individually_quantity', 1, $quantity, $product_id, $variation_id, $cart_item_data );
                    $in_cart_quantity = $cart_item_key ? $this->cart_contents[ $cart_item_key ]['quantity'] : 0;

                    if ( $in_cart_quantity > 0 ) {
                        throw new Exception( sprintf( '<a href="%s" class="button wc-forward">%s</a> %s', wc_get_cart_url(), __( 'View Cart', 'woocommerce' ), sprintf( __( 'You cannot add another &quot;%s&quot; to your cart.', 'woocommerce' ), $product_data->get_title() ) ) );
                    }
                }
2
My issue is a bit different from the one marked as Possible Duplicate question: stackoverflow.com/questions/27030769/…Manju

2 Answers

0
votes

Try this it will work:

add_filter('woocommerce_add_to_cart_sold_individually_quantity', 'vipcomment_change_quantity_to_zero', 10, 5);


  function vipcomment_change_quantity_to_zero($one, $quantity, $product_id, $variation_id, $cart_item_data ){
    $your_product_id = 96;
    if($product_id == $your_product_id){
      $product_cart_id = WC()->cart->generate_cart_id( $product_id );
      $in_cart = WC()->cart->find_product_in_cart( $product_cart_id );
      if($in_cart){
        return 0;
      }else{
        return $quantity;
      }
    }else{
      return $quantity;
    }

  }

  add_filter('woocommerce_add_to_cart_sold_individually_found_in_cart', 'vipcomment_is_product_exist_in_cart', 10, 5);
  function vipcomment_is_product_exist_in_cart($exist, $product_id, $variation_id, $cart_item_data, $cart_id){

    $your_product_id = 96;
    if($product_id == $your_product_id){
      return false;
    }else{
      return $exist;
    }

  }
-1
votes

Simplest way would be:

throw new Exception( sprintf( '<a href="%s" class="button wc-forward">%s</a> %s', 
  wc_get_cart_url(), __( 'View cart', 'woocommerce' ), 
  header( "Location: https://www.example.com/cart/" ) ) );

instead of that error. Be advised: this will redirect the user to the cart page ( where the product should already be in place ).