如何覆盖购物车中已有的数量? [英] How to override existing quantity already in cart?

查看:30
本文介绍了如何覆盖购物车中已有的数量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在这里遇到的问题是人们转到产品页面,设置他们想要该产品的数量并添加到购物车(然后将他们带到购物车页面).如果客户想对该产品进行进一步更改,则他们希望能够返回商店/产品页面(老实说这很奇怪,因为他们可以在购物车页面上执行此操作,但无论如何).但是当人们去更新产品页面上的数量时,不是更新数量,而是添加到该产品的现有数量上.

Problem I am having here is that people go to a Product page, set a quantity on how much they want of that product and add to cart (which than takes them to the cart page). Client wants the ability to go back to the shop/product page if they want to make further changes to that product (honestly this is strange, since they can do this on the cart page, but whatever). But when people go to update the quantity on the product page, instead of updating the quantity, it adds to the existing quantity for that product.

在产品页面多次提交数量时,如何让其更新现有数量?我可以在这里利用 woocommerce 循环吗?

How to get it to update the existing quantity when the quantity has been submitted more than once on the product page? Is there a woocommerce loop that I can take advantage of here?

推荐答案

谢谢大家,我已经挖掘了插件并编写了以下解决方案:

Thanks guys, I have dug through the plugin and coded the solution below:

add_action('woocommerce_add_to_cart_handler', 'update_product_in_cart', 11, 2);

function update_product_in_cart($p, $q) {
    global $woocommerce;
    $cartItem = $woocommerce->cart->cart_contents;
    $currentProductId = $q->id;
    $wCart = $woocommerce->cart->get_cart();

    // If cart already exists, and product exists, than remove product, and add the new product to it.
    if ($wCart)
    {
        $cart_item_keys = array_keys($wCart);

        foreach($cart_item_keys as $key)
        {
            foreach($cartItem as $item)
            {
                $productItemId = $item['product_id'];
                if ($productItemId == $currentProductId)
                {
                    // If you want to empty the entire cart...
                    // $woocommerce->cart->empty_cart();
                    // If you want to remove just the product from the cart...
                    $woocommerce->cart->set_quantity($key, 0);
                }
            }
        }
    }
    // This adds the product to the cart...
    return $q;
}

这被添加到functions.php,并且基本上,如果产品id存在于购物车中,它会移除产品并且返回$q添加新的产品信息.

This gets added to functions.php, and basically, if the product id exists in the cart, it removes the product and the return of $q adds in the new product info.

很有魅力!

这篇关于如何覆盖购物车中已有的数量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆