0

I am using the latest version of wordpress and Woocommerce. My Functionality is " Overriding the existing Quantity of Products already in cart". I already try this idea but its failure. See the Code and its errors.

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

Its Error is:

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
4

1 回答 1

0

这段代码就是答案,之前我在评论框中添加了......

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

于 2019-11-11T09:46:44.523 回答