0

ill try to hook change the discount percentage based on 3 different

for example:

  1. if costumer spend >= 200.000 they wiil have 10% discount
  2. if cosutumer spend >= 350.000 they will have 15% discount
  3. if costumer spend >= 500.000 they will have 20% discount

the question is how can i apply this discount in the selected product? and how to make thats manual, I mean that discount work when costumer input voucher code in the available colomn?

this is my code so far

add_action( 'woocommerce_cart_calculate_fees', 'discount_based_on_total', 
25, 1 );
function discount_based_on_total( $cart ) {

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

$total = $cart->cart_contents_total;

// Percentage discount (10%)
if( $total >= 200000 )
   $discount = $total * 0.1;
if( $total >= 350000 )
    $discount = $total * 0.15;
if( $total >= 500000 )
    $discount = $total * 0.20;
$cart->add_fee( __('discount', 'woocommerce'), -$discount );
}
angga
  • 89
  • 3
  • 9
  • yeah i know but that auto apply discount, how to make thats manual, I mean that discount work when costumer input voucher code in the available colomn? – angga May 20 '18 at 11:08

1 Answers1

1

You should also add upper limit for the first two conditions. Otherwise, you can fall into multiple if conditions.

For instance 390K is greater than 200K and also greater than 350K.

add_action( 'woocommerce_cart_calculate_fees', 'discount_based_on_total',25, 1 );
function discount_based_on_total( $cart ) {

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

    $total = $cart->cart_contents_total;

    // Percentage discount (10%)
    if( $total >= 200000 && $total < 350000 ){
       $discount = $total * 0.1;
    }
    else if( $total >= 350000  && $total < 500000 ){
        $discount = $total * 0.15;
    }
    else if( $total >= 500000 ){
        $discount = $total * 0.20;
    }
    else{
        $discount = 0;
    }

    $cart->add_fee( __('discount', 'woocommerce'), -$discount );
}
curiousBoy
  • 6,334
  • 5
  • 48
  • 56
  • If you reorder your checks, you don't have to add upper limits: `if ( $total >= 500000 ){ $discount = $total * 0.20; } else if( $total >= 350000 ){ $discount = $total * 0.15; } elseif( $total >= 200000 ){ $discount = $total * 0.1; } else { $discount = 0; }` – Camwyn Oct 14 '18 at 16:00