Answer the question
In order to leave comments, you need to log in
How to properly discount products in Woocommerce?
Hello.
I'm trying to make the following functionality:
apply a discount to all products of certain categories EXCEPT the first one added to the cart.
At the moment I have the following code (for the time being I am doing it for all categories, then I will add the code):
add_action('woocommerce_before_calculate_totals', 'discount', 10, 1);
function discount( $cart ) {
if (is_admin() && !defined('DOING_AJAX')) {
return;
}
if (did_action('woocommerce_before_calculate_totals') >= 2) {
return;
}
$count = 0;
$percentage = 50;
foreach ($cart->get_cart() as $cart_item) {
$count++;
if ($count === 1) {
continue;
}
$price = $cart_item['data']->get_price();
$discounted_price = $price * (1 - ($percentage / 100));
$cart_item['data']->set_price($discounted_price);
}
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question