【问题标题】:Remove item with $product_id - Woocommerce删除带有 $product_id 的项目 - Woocommerce
【发布时间】:2015-06-01 09:23:31
【问题描述】:

制作了一个功能,当客户达到特定数量时,他们会将产品添加到购物车中。

客户达到 3 级并添加产品的示例。

// Bonus products
$product_1 = '4751'; 
$product_2 = '4752'; 
$product_3 = '4753'; 

// Get cart value in a clean format
$cart_total = WC()->cart->get_cart_subtotal();
$cart_total = html_entity_decode($cart_total, ENT_QUOTES, 'UTF-8');
$cart_total_format = strip_tags($cart_total);
$cart_value = preg_filter("/[^0-9]/", "", $cart_total_format);
$sum_raw = $cart_value;

// Set the sum level 
$level3 = '1500';

// Check sum and apply product
if ($sum_raw >= $level3) {

// Cycle through each product in the cart and check for match
$found = 'false';
foreach (WC()->cart->cart_contents as $item) {
    global $product;
    $product_id = $item['variation_id'];

    if ($product_id == $product_3) {
        $found = 'true';
    }
}

// If product found we do nothing 
if ($found == 'true') {}
// else we will add it
else {
    //We add the product
    WC()->cart->add_to_cart($product_3);

如果客户决定删除项目,那么这个声明是正确的,我希望能够再次删除它。

if ($sum_raw < $level3) {

    // Trying to remove item
    foreach ($woocommerce->cart->get_cart() as $cart_item_key => $cart_item) {
        if ($cart_item['variation_id'] == $product_3) {

            //remove single product
            WC()->cart->remove_cart_item($product_3);
        }
    }
}

我无法从购物车中删除产品。有什么想法在这里做错了吗?一直在四处寻找,但没有找到任何适合我的解决方案。

解决方案

在@Rohil_PHPBeginner 和@WisdmLabs 的帮助下,我找到了这个为我完成工作的解决方案。

global $woocommerce;
// Check if sum
if ($sum_raw < $level3) {
    foreach ($woocommerce->cart->get_cart() as $cart_item_key => $cart_item) {

        if ($cart_item['variation_id'] == $product_3) {
            //remove single product
            $woocommerce->cart->remove_cart_item($cart_item_key);
        }
    }
}

【问题讨论】:

  • WC_Cart::remove_cart_item($cart_item_key);
  • 我应该改变 WC()->cart->remove_cart_item($product_3);为此?
  • 变量 $product_3 是什么?
  • $product_3 = '4753'; , 是产品的变体ID
  • remove_cart_item() 它接受参数为 $cart_item_key

标签: php wordpress woocommerce


【解决方案1】:

我认为您错误地使用了remove_cart_item。如果你通过documentation,你会发现它接受cart_item_key作为参数(正如wisdmLabs在评论中提到的那样)。

你是这样使用它的:

WC()->cart->remove_cart_item($product_3);

试试这个:

WC()->cart->remove_cart_item($cart_item_key);

更新该行后,我认为您将能够删除产品。

【讨论】:

  • 谢谢,这帮助我解决了这个问题。将使用解决方案更新我的帖子以供其他人查看。
  • 链接失效。请更新它。
【解决方案2】:

将此用于最新版本的 WooCommerce

$cartId = WC()->cart->generate_cart_id( 'PRODUCT ID' );
$cartItemKey = WC()->cart->find_product_in_cart( $cartId );
WC()->cart->remove_cart_item( $cartItemKey );

将产品 ID 替换为您的。

【讨论】:

    猜你喜欢
    • 2013-11-11
    • 1970-01-01
    • 2014-05-11
    • 1970-01-01
    • 1970-01-01
    • 2020-11-24
    • 2011-08-20
    • 2017-08-29
    • 1970-01-01
    相关资源
    最近更新 更多