How to add items to cart with unique cart key . i dont want to update the quantity of cart items cart already have
eg. if we have 2 items in cart , then i want to add two more items to cart , instead of an item with quantity 4 , i need two cart items with quantity 2
So take a look at this method in add_to_cart()
in woocommerce/includes/class-wc-cart.php
// Load cart item data - may be added by other plugins.
$cart_item_data = (array) apply_filters( 'woocommerce_add_cart_item_data', $cart_item_data, $product_id, $variation_id, $quantity );
// Generate a ID based on product ID, variation ID, variation data, and other cart item data.
$cart_id = $this->generate_cart_id( $product_id, $variation_id, $variation, $cart_item_data );
You see the $cart_id
takes in $cart_item_data
which you can modify to be different from the previous items in order to generate unique id's.
You need this custom hooked function that will add to cart items a generated unique key:
add_filter( 'woocommerce_add_cart_item_data', 'set_custom_cart_item_key', 10, 4 );
function set_custom_cart_item_key( $cart_item_data, $product_id, $variation_id, $quantity ) {
$cart_item_data['unique_key'] = md5( microtime().rand() );
WC()->session->set( 'custom_data', $cart_item_data['unique_key'] );
return $cart_item_data;
}
Code goes in function.php file of your active child theme (or active theme). Tested and work.
It will avoid increasing item quantity when same product is added to cart… so you will have separated cart items instead…
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.