用$ product_id删除商品 - Woocommerce

用$ product_id删除商品 - Woocommerce

问题描述:

制作了一项功能,当顾客在购物车达到特定金额时将其添加到购物车中。

客户达​​到等级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); 
     } 
    } 
} 
+0

WC_Cart :: remove_cart_item($ cart_item_key); – WisdmLabs

+0

Chould我改变WC() - > cart-> remove_cart_item($ product_3);为了那个原因 ? –

+0

这是什么变量$ product_3? – WisdmLabs

我想你错误地使用了remove_cart_item。如果您经历了documentation,您会发现它接受cart_item_key作为参数(如评论中提到的wisdmLabs)。

您正在使用它像这样:

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

试试这个:

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

更新该行之后,我想你一定能够消除产品。

+0

谢谢,这帮助我解决了这个问题。将更新我的帖子与其他人看到的解决方案。 –

+1

很高兴它为你工作。快乐编码! –