How to add discount to cart total?

I need to add discount according to number of product in cart and this discount will apply on total of cart. Is there any other option without use of coupons?


This code should work:

add_action('woocommerce_before_cart_table', 'discount_when_produts_in_cart');
function discount_when_produts_in_cart( ) {
    global $woocommerce;
    if( $woocommerce->cart->cart_contents_count > 3 ) {
        $coupon_code = 'maryscode';
        if (!$woocommerce->cart->add_discount( sanitize_text_field( $coupon_code ))) {
        echo '<div class="woocommerce_message"><strong>You have more than 3 items in your cart, a 10% discount has been added.';

The above will apply the coupon "maryscode" to the cart if there are 4 or more products in the customers cart.

EDIT: Add the following to your css

    display: none !important;

I prefer this way, more cleaner I think

// Hook before calculate fees
add_action('woocommerce_cart_calculate_fees' , 'add_custom_fees');

 * Add custom fee if more than three article
 * @param WC_Cart $cart
function add_custom_fees( WC_Cart $cart ){
    if( $cart->cart_contents_count < 3 ){

    // Calculate the amount to reduce
    $discount = $cart->subtotal * 0.1;
    $cart->add_fee( 'You have more than 3 items in your cart, a 10% discount has been added.', -$discount);

Need Your Help

What is the simplest way to assign DNS name to EC2 instance using Route 53 service?

amazon-ec2 amazon-web-services dns amazon-route53

I have got a domain registered with GoDaddy and an EC2 instance with public elastic IP and I'm trying to use Amazon "Route 53" service to map the DNS name to my instance.

How to deal with "data of class uneval" error from ggplot2?

r ggplot2

While trying to overlay a new line to a existing ggplot I am getting the following error: