Skip to content

Separate in multiple lines when we add the same product more than once to the cart

Sometimes, it is interesting to be able to separate the same product in multiple lines of the WooCommerce cart, with different quantities in each line. This can be interesting when selling by weight, since the customer may want to buy different amounts of the same product (to separate it into bags, for example).

In order to separate the same product into multiple lines each time we add it to the cart, we can use a simple filter:

  • woocommerce_add_cart_item_data:
    With this filter we can add data to each order line, when it is added to the cart. The trick is to add a unique (different) variable each time the product is added to the cart. In this way, WooCommerce interprets that they are different order lines.

Below is the snippet to integrate this new column:

add_filter( 'woocommerce_add_cart_item_data', function ( $cart_item_data, $product_id ) {
    $uid = md5( microtime() . rand() ); //Any "unique" value
    $cart_item_data['uid'] = $uid;
    return $cart_item_data;
}, 10, 2);

In case you want to limit the quantity to 1 each time it is added to the cart, you can use this other line of code:

add_filter( 'woocommerce_is_sold_individually', '__return_true' );