使用$ product_id删除商品-Woocommerce [英] Remove item with $product_id - Woocommerce
问题描述
提供一种功能,客户可以在达到特定数量时将其添加到购物车中.
Made a function where the customer get a product added to the cart when they reach a specific amount.
客户何时达到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);
如果客户决定删除商品,那么此声明为true,我希望能够再次删除它.
If customer decides to remove item's so this statement is true i want to be able to remove it again.
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);
}
}
}
Am无法将产品从购物车中移除.有什么想法在这里做错了吗?一直在寻找找不到适合我的解决方案的地方.
Am do not manage to remove the product from cart. Any ideas what am doing wrong here? Have been searching around without finding any solution that works for me.
解决方案
在@Rohil_PHPBeginner&的帮助下@WisdmLabs我来到了这个为我完成工作的解决方案.
With help from @Rohil_PHPBeginner & @WisdmLabs I came to this solution that did the job for me.
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);
}
}
}
推荐答案
我认为您使用的remove_cart_item
错误.如果您查看文档,您会发现它接受 cart_item_key 作为参数(如注释中提到的wisdmLabs).
I think you're using remove_cart_item
incorrectly. If you go through the documentation, you will find that it accepts cart_item_key as parameter (as wisdmLabs mentioned in comment).
您正在像这样使用它:
WC()->cart->remove_cart_item($product_3);
尝试以下方法:
WC()->cart->remove_cart_item($cart_item_key);
更新该行之后,我认为您将能够删除产品.
After updating that line, I think you will able to remove product.
这篇关于使用$ product_id删除商品-Woocommerce的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!