L
L
Lev Aleksandrov2022-01-23 17:30:27
WordPress
Lev Aleksandrov, 2022-01-23 17:30:27

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);
    }
}


Everything works, but I would like to somehow show the user that a discount has been applied to the products.
For example, I would like the "Total" column (subtotal product field) to display the amount including the discount.
With the above code, the "Cost" column changes and, accordingly, the "Total" column.
61ed663eef539395054062.png

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question