Home > Software design >  Woocommerce - Remove Only one Unit of a product from cart
Woocommerce - Remove Only one Unit of a product from cart

Time:12-23

I am working on this woocommerce search function that uses AJAX to fetch products on every keystroke and that gives the possibility to add or remove units of a certain product to cart right from the instant search results modal.

In each search result there is this group of two buttons that allow the client to add 1 or remove 1 product from cart at a time. I managed to make the add to cart button work but can't seem to find a good solution to remove just one single unit from cart instead of all of them at once.

enter image description here

I have tried this:

function remove_product_from_cart_programmatically() {
   if ( is_admin() ) return;
   $product_id = 282;
   $product_cart_id = WC()->cart->generate_cart_id( $product_id );
   $cart_item_key = WC()->cart->find_product_in_cart( $product_cart_id );
   if ( $cart_item_key ) WC()->cart->remove_cart_item( $cart_item_key );
}

but it removes all products with that ID at once.

I want to be able to remove unit by unit in case there are items in cart with that ID.

This is the code I have right now for the remove from cart button:

add_action('wp_ajax_search_remove_from_cart', 'search_remove_from_cart');
add_action('wp_ajax_nopriv_search_remove_from_cart', 'search_remove_from_cart');

// handle the ajax request
function search_remove_from_cart()
{
    $product_id = $_REQUEST['product_id'];
    WC()->cart->remove_cart_item($product_id);

    $products_in_cart = WC()->cart->get_cart_item_quantities($product_id);
    $updated_qty = $products_in_cart[$product_id];

    // in the end, returns success json data
    wp_send_json_success(["Product removed from cart Successfuly!", $updated_qty]);

    // or, on error, return error json data
    wp_send_json_error(["Could not remove the product from cart"]);
}

Is there any function to remove only one unit of a certain product from cart?

Thank you all !

CodePudding user response:

You have to change the quantity instead of removing the product. Number of product units in the cart = quantity.

Try something like this:

function remove_from_cart(){
    $product_id = 47;
    $cart = WC()->cart;
    $product_cart_id = $cart->generate_cart_id( $product_id );
    $cart_item_key = $cart->find_product_in_cart( $product_cart_id );
    if ( $cart_item_key ){
        $quantity = $cart->get_cart_item($cart_item_key)['quantity'] - 1;
        $cart->set_quantity($cart_item_key, $quantity);
    }
}

  • Related