• Hi guys,

    In WooCommerce, I’m trying to add items to the cart and treat them individually, even if they are the same item with the same variations. So if I had “Mountain Bike – Red” twice, instead of incrementing the quantity to two, it adds a new row with the same item

    I found a post on these forums (https://wordpress.org/support/topic/how-to-treat-cart-items-individually-rather-than-grouped-product?replies=9 but it’s now closed) which had exactly what I was looking for:

    When an item gets added to the cart, a ‘key’ for that individual item in the cart is created based on the item being added and it’s associated meta data. If the item and it’s meta data are identical to another item in the cart, then the generated key will be identical too, and the the quantity of the item already in the cart will simply be incremented by the quantity being added.

    To fix this, you have to hook into the add-to-cart function and add some unique meta data, like so:

    add_filter('woocommerce_add_to_cart_item_data','namespace_force_individual_cart_items',10,2);
    function namespace_force_individual_cart_items($cart_item_data, $product_id)
    {
    	$unique_cart_item_key = md5(microtime().rand()."Hi Mom!");
    	$cart_item_data['unique_key'] = $unique_cart_item_key;
    
    	return $cart_item_data;
    }

    The problem I am facing now is that I want the same behaviour to happen in the cart when the quantity gets manually updated to more than 1.

    I have tried almost every “cart” related filter I could find, searching on the WooCommerce docs, doing a mass find on Sublime on the “woocommerce” plugin folder for “update cart”, “cart”, etc, but I’m afraid I’m not really sure which on to use. The one I have worked on the most is this one:

    add_action('woocommerce_before_calculate_totals', 'change_cart_item_price');
    function change_cart_item_price($cart_object) {
    
        global $woocommerce;
    
        foreach ($woocommerce->cart->cart_contents as $cart_key => $cart_item_array) {
            if($cart_item_array['quantity'] > 1 ) {
                $cart_item_key = md5(microtime().rand()."Hi Mom!");
                $cart_item_data['unique_key'] = $cart_item_key;
    
                $woocommerce->cart->set_quantity($cart_item_key, '1');
            }
       }
    
       return $cart_object;
    }

    Here I’m running through the cart object, checking if the quantity is bigger than one and if it is I assign a new key. I really don’t know if I’m doing the right thing or if I’m completely off the track so any pointers would be really appreciated.

    Please let me know if you need more info and I’ll try to provide everything I can.

    Thanks a lot in advance!

  • The topic ‘[Plugin: WooCommerce] Add cart items individually regardless of quantity’ is closed to new replies.