2

I Would like in woocommerce cart, that customers will get a 20% discount, but I want to limit the discounted amount to $500 for example.

Is that possible in WooCommerce?

Thanks.

LoicTheAztec
  • 229,944
  • 23
  • 356
  • 399

1 Answers1

4

This can be done with ease using woocommerce_cart_calculate_fees hook and the WC_cart method add_fee(). Then if you use a negative fee, it becomes then a DISCOUNT.

In this function the discount is calculate from the cart subtotal excluding taxes (and you can easily change it to total including taxes).

Here is the code:

add_action( 'woocommerce_cart_calculate_fees', 'custom_limited_discount', 10, 1 );
function custom_limited_discount($cart_object) {

    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

    // Here 20 % of discount
    $discount_percent = 0.2;

    // Here the max discounted amount
    $max_discount = 500;

    // Here are some different cart totals
    $cart_subtotal_excl_tax = WC()->cart->subtotal_ex_tax;
    $cart_subtotal = WC()->cart->subtotal;
    $cart_total = WC()->cart->total;

    $discount = 0;

    // CALCULATION with subtotal excluding taxes
    $calculation = $cart_subtotal_excl_tax * $discount_percent;

    // Limiting the discount to $max_discount
    if ( $calculation > $max_discount ) {
        $discount -= $max_discount;
    } else {
        $discount -= $calculation;
    }

    $discount_text_output = __( 'Discount (20 %)', 'woocommerce' );

    // Adding the discount
    $cart_object->add_fee( $discount_text_output, $discount, false );
    // Note: Last argument in add_fee() method is related to applying the tax or not to the discount (true or false)
}

This code is tested and is fully functional.

Code goes in function.php file of your active child theme (or theme). Or also in any plugin php files.

Note: Last argument in add_fee() method is related to applying the tax or not to the discount (true or false).

LoicTheAztec
  • 229,944
  • 23
  • 356
  • 399
  • sir.as like My coupon code is "MAX500" if anyone applied that coupon code then they will get 20% discount from $500 to $2500 and if the cart total is more than $2500 then the customer discounted by max $500 amount. please concern and guide me through this issue – Developer Indglobal Dec 14 '16 at 12:30
  • @RaviShankar Sorry but in your question you didn't ask this, so please as this answer is the good one related to your question accept it… After that, I have seen your newest question that is exactly what you are asking me here in your comment and I will try to answer it. But for coupons, things are much more complicated, to make it as you would like and may be not possible this way. – LoicTheAztec Dec 14 '16 at 15:51