Search code examples
phpwordpresswoocommercecartdiscount

Automatically add a percentage discount if WooCommerce cart contains at least X products


I am trying to create an automated discount that kicks in when and if the cart contains a minimum of three products or more.

If and when that is, a discount of 10% should be given no matter if the customer is logged in or not.

This is the code I'm trying to get to work (without success).

add_action( 'woocommerce_cart_calculate_fees', 'wc_discount_when_more_than_three', 10, 1 );
function wc_discount_when_more_than_three( $cart ) {

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

        return;

    $percentage = 10; // 10% discount when cart has a minimum of three products
    $discount = 0;

    // check all cart items
    foreach ( $cart->get_cart() as $cart_item ) {

    // when quantity is more than 3
    if( $cart_item['quantity'] > 3 ) {

    // give 10% discount on the subtotal
    $discount = $percentage / 100;
    }
}
    
    if( $discount > 0 )
    $cart->add_fee( __( '10% OFF', 'woocommerce' ) , -$discount );
}

Solution

  • It depends on whether you want to count the number of products in the cart or the number of product quantities (contents).

    In my answer I have illustrated both, uncomment/delete/adjust to your needs.

    function action_woocommerce_cart_calculate_fees( $cart ) {
        if ( is_admin() && ! defined( 'DOING_AJAX' ) )
            return;
        
         // Percentage
        $percentage = 10;
    
        /* Count contents in cart
         *
         * Product A: quantity in cart: 4 
         * Product B: quantity in cart: 1 
         * Product C: quantity in cart: 2
         *
         * count = 7
         *
         */
        //$count = $cart->cart_contents_count;
        
        /* Count products in cart
         *
         * Product A
         * Product B 
         * Product C
         *
         * count = 3
         */
        $count = count( $cart->get_cart() );
        
        // Greater than
        if ( $count > 3 ) {
            // Get subtotal
            $subtotal = $cart->subtotal;
            
            // Calculate
            $discount = ( $subtotal / 100 ) * $percentage;
            
            // Give % discount on the subtotal
            $cart->add_fee( sprintf( __( '%s OFF', 'woocommerce'), $percentage . '%' ), -$discount );
        }
    }
    add_action( 'woocommerce_cart_calculate_fees', 'action_woocommerce_cart_calculate_fees', 10, 1 );