Menu Close

Add discount amount based on the cart total Woocommerce

Add discount amount based on the cart total Woocommerce

Code Snippet for adding discount for cart total in woocommerce

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

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

    $total = $cart->cart_contents_total;
    $discount = $total * 0.1;
 //10% Discount
    
    $cart->add_fee( __('discount', 'woocommerce'), -$discount );
} 

Also you can discount variations based on the cart total.

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

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

    $total = $cart->cart_contents_total;

    if( $total >= 200 &amp;amp;&amp;amp; $total < 500 ){
       $discount = $total * 0.1;
 // Percentage discount (10%)
    }
    else if( $total >= 500  &amp;amp;&amp;amp; $total < 1000 ){
        $discount = $total * 0.15;
 // Percentage discount (15%)
    }
    else if( $total >= 1000 ){
        $discount = $total * 0.20;
 // Percentage discount (20%)
    }
    else{
        $discount = 0;
 // Percentage discount (0%)
    }

    $cart->add_fee( __('discount', 'woocommerce'), -$discount ); 
Posted in PHP, WooCommerce, WordPress

You can also read...