Split cart items when quantity is updated on cart page in WooCommerce

两盒软妹~` 提交于 2020-12-13 12:08:49

问题


I want to split cart items of same product in individual lines. When I increase quantity on single product page and add to cart, it shows as separate cart items.

Im using WooCommerce - Treat cart items separate if quantity is more than 1 answer code.

I want when quantity is updated on cart page and clicked on 'Update cart', then items must split on individual lines.

How can I do that?


回答1:


The code below will split items on individual lines when quantity is updated on the cart page.

Comment with explanation added to the code.

function 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', 'on_action_cart_updated', 20, 1 );


来源:https://stackoverflow.com/questions/59878382/split-cart-items-when-quantity-is-updated-on-cart-page-in-woocommerce

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!