如何覆盖购物车中已有的产品数量?

时间:2016-10-24 14:39:51

标签: php woocommerce cart function-overriding product-quantity

我正在使用最新版本的wordpress和Woocommerce。 我的功能是"覆盖已在购物车中的现有产品数量"。我已经试过这个idea,但它失败了。请参阅代码及其错误。

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

错误是:

Catchable fatal error: Object of class WC_Product_Grouped could not be converted to string in plugins\woocommerce\includes\class-wc-form-handler.php on line 715

1 个答案:

答案 0 :(得分:0)

此代码就是答案,以前我在注释框中添加了...。

add_action('woocommerce_add_to_cart_handler','update_product_in_cart',11,2);函数update_product_in_cart($ p,$ q){全局$ woocommerce; $ cartItem = $ woocommerce->购物车-> cart_contents; $ currentProductId = $ q-> id; $ wCart = $ woocommerce->购物车-> get_cart(); 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){$ woocommerce->购物车-> set_quantity($ key,0); }}}}返回$ q; }