Search code examples
phpwordpresswoocommercecartproduct-quantity

Set all items in saperated rows even if product is added twice in WooCommerce cart


I tried using Separated cart items in Woocommerce when quantity is more than 1 answer code, but after adding product if I come back to the same product page and add it again, it's not adding to new row But increasing the quantity which I do not want, I want new row as a new item every time.

add_action( 'woocommerce_add_to_cart', 'mai_split_multiple_quantity_products_to_separate_cart_items', 10, 6 );
function mai_split_multiple_quantity_products_to_separate_cart_items( $cart_item_key, $product_id, $quantity, $variation_id, $variation, $cart_item_data ) {

    // 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 ( $i = 1; $i <= $quantity -1; $i++ ) {
            /**
             * Set a unique key.
             * This is what actually forces the product into its own cart line item
             */
            $cart_item_data['unique_key'] = md5( microtime() . rand() . "Hi Mom!" );

            // 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_data );
        }
    }
}

Solution

  • To solve this issue, use the following code replacement:

    add_filter( 'woocommerce_add_cart_item_data', 'filter_add_cart_item_data' );
    function filter_add_cart_item_data( $cart_item_data ) {
        if ( ! isset($cart_item_data['unique_key']) ) {
            $cart_item_data['unique_key'] = md5(microtime().rand());
        }
        return $cart_item_data;
    }
    
    
    add_action( 'woocommerce_add_to_cart', 'split_cart_items_by_quantity', 10, 6 );
    function split_cart_items_by_quantity( $cart_item_key, $product_id, $quantity, $variation_id, $variation, $cart_item_data ) {
        if ( $quantity == 1 ) return;
            
        // Keep the product but set its quantity to 1
        WC()->cart->set_quantity($cart_item_key, 1);
    
        // Loop through each unit of item quantity
        for ( $i = 1; $i <= $quantity -1; $i++ ) {
            // Make each quantity item unique and separated
            $cart_item_data['unique_key'] = md5(microtime().rand());
    
            // Add each item quantity as a separated cart item
            WC()->cart->add_to_cart( $product_id, 1, $variation_id, $variation, $cart_item_data );
        }
    }
    

    Code goes in functions.php file of your child theme (or in a plugin). Tested and works.