[DRUPAL][UBERCART] How to remove an item from cart?

| | 1 min read

If you are working on a Drupal website with Ubercart and if you are handling custom product mechanisms programmatically, one of the main task you may come across can be, 'removing an item from your cart', when a particular condition is satisfied. If you are facing any difficulty with removing items from cart, I may have a solution for you.

By default Ubercart provides custom function named uc_cart_remove_item() to remove an item.

uc_cart_remove_item(node_id, cart_id, product_data)

As you can see that the function requires three parameters:

  1. Node id - Node id of the product that you want to delet.e
  2. Cart id - You can get the current cart id from uc_cart_get_id().
  3. Data - Data of the product that you want to delete.

If you go through the Ubercart API of the function you can see that the definition specifies the data parameter by default takes an empty array. However if you are trying to delete a node by just giving the node id it will not work.

But you can remove the item by running a simple database query given below.

db_query("DELETE FROM {uc_cart_products} WHERE cart_id = '%s' AND nid = %d", uc_cart_get_id() , $nid);

Hope this helped you solve your problem.