разделить элементы корзины, когда количество обновляется на странице корзины - PullRequest
0 голосов
/ 23 января 2020

Я хочу разделить элементы корзины одного и того же продукта на отдельные строки. Когда я увеличиваю количество на странице одного товара и добавляю в корзину, он отображается как отдельные элементы корзины. Я использовал следующий код:

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

}

}

Я хочу, чтобы, когда количество обновлялось на странице корзины и нажималось «Обновить корзину», тогда позиции должны разделяться на отдельные строки. Как я могу это сделать?

1 Ответ

0 голосов
/ 23 января 2020
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 );
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...