如果产品已存在于购物车中,请增加 WooCommerce 购物车页面中的产品数量

问题描述 投票:0回答:1

如果产品已存在于购物车中,我想增加 WooCommerce 购物车页面上的产品数量。

我尝试了这段代码

if ( 'same_product_added_to_cart' === $customer_gets_as_free ) {
   foreach ( $main_product_id as $main_product_single ) {
        $main_product_single = intval( $main_product_single );
    foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
        if ( $cart_item['product_id'] === $main_product_single ) {
        // Get the current quantity
        $current_quantity = $cart_item['quantity'];
        // Increase the quantity by one
        $new_quantity = $current_quantity + 1;

        // Update the cart with the new quantity
        WC()->cart->set_quantity( $cart_item_key, $new_quantity );

        break; // Exit the loop since we have found our product
       }
       }
   }
}

它不起作用,相反,它触发了无限数量的循环并给出了错误。我在这里做错了什么。并且

add_to_cart()
函数也会给出相同类型的错误。

php wordpress woocommerce cart product-quantity
1个回答
0
投票

通常,如果在添加到购物车时没有将不同的自定义购物车项目数据添加到购物车项目,WooCommerce 会自行执行此操作。

您的代码中存在错误和缺少步骤。

以下是合并重复产品(购物车商品)的方法:

add_action( 'woocommerce_before_calculate_totals', 'merge_duplicated_products_in_cart');
function merge_duplicated_products_in_cart( $cart ) {
    if ((is_admin() && !defined('DOING_AJAX')))
        return;

    if (did_action('woocommerce_before_calculate_totals') >= 2)
        return;

    $items_data = $item_update = []; // initializing

    // Loop through cart items
    foreach ( $cart->get_cart() as $cart_item_key => $cart_item ) {
        $product_id = $cart_item['data']->get_id();
        $quantity   = $cart_item['quantity'];

        // Check if the product exists
        if( in_array($product_id, array_keys($items_data)) ) {
            // Same product found
            $item_update['item_qty'] = $items_data[$product_id]['qty'] + $quantity; // Set cumulated quantities
            $item_update['item_key'] = $items_data[$product_id]['key']; // Add first product item key
            $item_update['item_remove'] = $cart_item_key; // Add current item key (product to be removed)
            break; // Stop the loop
        } 
        // Add product_id, cart item key and item quantity to the array (for each item)
        else {
            $items_data[$product_id] = array(
                'key' => $cart_item_key,
                'qty' => $quantity
            );
        }
    }
    unset($items_data); // delete the variable

    if ( ! empty($item_update) ) {
        $cart->remove_cart_item($item_update['item_remove']); // remove last item (same product)
        $cart->set_quantity($item_update['item_key'], $item_update['item_qty']); // Update quantity on first item(same product)
        unset($item_update); // delete the variable
    }
}

代码位于子主题的functions.php 文件中(或插件中)。已测试并有效。

© www.soinside.com 2019 - 2024. All rights reserved.