I have a code in WooCommerce that once you buy products with the ID:
1561, 1919, 1568, 1562, 1563, 1564, 1565, 1566, 1567
So, the second product is NIS 10.
The product on which the discount applies is only the product with ID 1561
The code works well, but as soon as I want to have multiple promotions, it doesn’t work.
For example:
If you buy two products then I want the customer to be able to get product 1561 twice for NIS 10
If you buy five products, then I want the customer to be able to receive five times the product 1561 for NIS 10
And so on…
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
}
}
}
}
2
Answers
I think you need to first calculate the amount of max discounted product count, and then set the price for the appropriate product:
Keep in mind that this allows customers to always buy 1561 for NIS 10. I think that’s your intention, but I’m not sure.
In the following code, will change the price of a specific cart item (with a minimal quantity of 2), enabled, based and calculated from some defined products count (cart items count).
You will need to define in the first function:
Code goes in functions.php file of your active child theme (or active theme). Tested and work.