在WooCommerce中的购物车页面上更新数量时拆分购物车项目

时间:2020-01-23 12:17:06

标签: wordpress woocommerce product cart hook-woocommerce

我想将同一产品的购物车项目拆分为单独的行。当我在单个产品页面上增加数量并添加到购物车时,它显示为单独的购物车项目。

我正在使用WooCommerce - Treat cart items separate if quantity is more than 1答案代码。

我想要在购物车页面上更新数量并单击“更新购物车”时,项目必须在单独的行上拆分。

我该怎么做?

1 个答案:

答案 0 :(得分:1)

当购物车页面上的数量更新时,下面的代码将在单独的行上拆分项目。

注释,并在代码中添加了解释。

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 );