【发布时间】:2021-08-25 07:47:23
【问题描述】:
我想根据 WooCommerce 中的购物车数量添加一定的免费礼物。
假设:
- 少于 1500 - 没有免费礼物
- 介于或等于 1500 - 1999 - 添加免费产品 (1)
- 大于或等于 2000 - 添加另一个免费产品 (2),删除免费产品 (1)
基于Add free gifted product for a minimal cart amount in WooCommerce 答案代码,如果我添加 1 个元素,它会起作用,但如果我添加更多,它就会停止工作。
这是我的代码尝试:
// Add free gifted product for specific cart subtotal
add_action('woocommerce_before_calculate_totals', 'check_free_gifted_product');
function check_free_gifted_product($cart)
{
if (is_admin() && !defined('DOING_AJAX'))
return;
// Settings
$free_product_id = 158;
$targeted_subtotal = 1500;
$targeted_subtotal_max = 2000;
$cart_subtotal = 0; // Initializing
// Loop through cart items (first loop)
foreach ($cart->get_cart() as $cart_item_key => $cart_item) {
// When free product is is cart
if ($free_product_id == $cart_item['product_id']) {
$free_key = $cart_item_key;
$free_qty = $cart_item['quantity'];
$cart_item['data']->set_price(0); // Optionally set the price to zero
} else {
$cart_subtotal += $cart_item['line_total'] + $cart_item['line_tax'];
}
}
// If subtotal match and free product is not already in cart, add it
if (!isset($free_key) && $cart_subtotal >= $targeted_subtotal && $cart_subtotal <= $targeted_subtotal_max) {
$cart->add_to_cart($free_product_id);
}
// If subtotal doesn't match and free product is already in cart, remove it
elseif (isset($free_key) && $cart_subtotal < $targeted_subtotal || $cart_subtotal > $targeted_subtotal_max) {
$cart->remove_cart_item($free_key);
}
// Keep free product quantity to 1.
elseif (isset($free_qty) && $free_qty > 1) {
$cart->set_quantity($free_key, 1);
}
}
有什么建议吗?
【问题讨论】:
标签: php wordpress woocommerce product cart