我在 WordPress WooCommerce 中有一个代码,一旦您使用 ID 购买产品: 1561、1919、1568、1562、1563、1564、1565、1566、1567 所以,第二个产品是 NIS 10。
优惠商品仅限ID 1561的商品 代码运行得很好,但是一旦我想要有多个促销,它就不起作用了。
例如: 如果您购买两种产品,那么我希望客户能够以 10 新谢克尔的价格获得两次产品 1561 如果您购买五种产品,那么我希望客户能够以 NIS 10 收到五倍产品 1561 等等...
add_action('woocommerce_before_calculate_totals', 'change_second_item_price', 10, 1);
function change_second_item_price($cart) {
if (is_admin() && !defined('DOING_AJAX')) {
return;
}
$discounted_product_id = 1561;
$new_regular_price = 10; // NIS 10
// Initialize count for the target products
$target_product_count = 0;
// Loop through cart items
foreach ($cart->get_cart() as $cart_item_key => $cart_item) {
$product_id = $cart_item['product_id'];
// Check if the product is one of the target products
if (in_array($product_id, array(1561, 1919, 1568, 1562, 1563, 1564, 1565, 1566, 1567))) {
$target_product_count += $cart_item['quantity'];
// Check if it's the discounted product and change the regular price
if ($product_id == $discounted_product_id && $target_product_count >= 2) {
$cart_item['data']->set_regular_price($new_regular_price);
$cart_item['data']->set_price($new_regular_price); // Also set the current price to the regular price
break; // Stop the loop after changing the regular price for the second item of the discounted product
}
}
}
}
帮助更改代码。
我认为你需要先计算最大折扣产品数量,然后为适当的产品设置价格:
add_action('woocommerce_before_calculate_totals', 'change_second_item_price', 10, 1);
function change_second_item_price($cart) {
if (is_admin() && !defined('DOING_AJAX')) {
return;
}
$discounted_product_id = 1561;
$new_regular_price = 10; // NIS 10
// Initialize count for the target products
$target_product_count = 0;
// Loop through cart items
foreach ($cart->get_cart() as $cart_item_key => $cart_item) {
$product_id = $cart_item['product_id'];
// Check if the product is one of the target products
if (in_array($product_id, array(1561, 1919, 1568, 1562, 1563, 1564, 1565, 1566, 1567))) {
$target_product_count += $cart_item['quantity'];
}
}
// Loop through cart items again, to find the discounted product
foreach ($cart->get_cart() as $cart_item_key => $cart_item) {
$product_id = $cart_item['product_id'];
// Check if it's the discounted product and change the regular price
if ($product_id == $discounted_product_id && $target_product_count >= $cart_item['quantity']) {
$cart_item['data']->set_regular_price($new_regular_price);
$cart_item['data']->set_price($new_regular_price); // Also set the current price to the regular price
}
}
}
请记住,这允许客户始终以 10 新谢克尔购买 1561。我认为这是您的意图,但我不确定。