製作了一項功能,當顧客在購物車達到特定金額時將其添加到購物車中。
客戶達到等級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); – WisdmLabs
Chould我改變WC() - > cart-> remove_cart_item($ product_3);爲了那個原因 ? –
這是什麼變量$ product_3? – WisdmLabs