How to add the same product as an individual cart item instead of changing quantity in WooCommerce

Photo of author
Written By geekerhub

Lorem ipsum dolor sit amet consectetur pulvinar ligula augue quis venenatis. 

Sometimes, we can across such requirements from the client that they need to show the same product if added multiple times as separate cart items instead of changing the quantity. In this case, we need to do some customization on Add to cart button and the update quantity hook on the cart page.

One can achieve this by pasting the below code in the functions.php file of your active theme.

<?php
//This code is used to make the product as individual items when Adding product to the cart
function geeker_force_individual_cart_items( $cart_item_data, $product_id ) {
  $unique_cart_item_key = md5( microtime() . rand() );
  $cart_item_data['unique_key'] = $unique_cart_item_key;

  return $cart_item_data;
}
add_filter( 'woocommerce_add_cart_item_data', 'geeker_force_individual_cart_items', 10, 2 );
?>
<?php
//This code is used to make the product as individual items when Updating the product on cart page
function geeker_on_action_cart_updated( $cart_updated ) {
    if ( $cart_updated ) {
        // Get cart
        $cart_items = WC()->cart->get_cart();

        foreach ( $cart_items as $cart_item_key => $cart_item ) {
            $quantity = $cart_item['quantity'];

            // If product has more than 1 quantity
            if ( $quantity > 1 ) {

                // Keep the product but set its quantity to 1
                WC()->cart->set_quantity( $cart_item_key, 1 );

                // Run a loop 1 less than the total quantity
                for ( $j = 1; $j <= $quantity -1; $j++ ) {
                    // Set a unique key.
                    $cart_item['unique_key'] = md5( microtime() . rand() . "Hi Mom!" );

                    // Get vars
                    $product_id 	= $cart_item['product_id'];
                    $variation_id 	= $cart_item['variation_id'];
                    $variation 		= $cart_item['variation'];

                    // Add the product as a new line item with the same variations that were passed
                    WC()->cart->add_to_cart( $product_id, 1, $variation_id, $variation, $cart_item );
                }
            }
        }
    }
}
add_action( 'woocommerce_update_cart_action_cart_updated', 'geeker_on_action_cart_updated', 20, 1 );
?>

Leave a Comment