Halloween Sale 15% off Ends in See the plans
PHP

Spend More, Save More Discount Tiers

Gives a bigger percentage discount as the cart subtotal grows, for example 5% over 100 and 10% over 200, and tells shoppers how close they are to the next tier.

Don’t have WPIDE yet? Install it on your site

Code

$wpide_spend_tiers = array( 100 => 5, 200 => 10, 400 => 15 ); // Subtotal => percent off.

$wpide_spend_tier = function ( $subtotal ) use ( $wpide_spend_tiers ) {
    $current = array( 0, 0 );
    $next    = null;
    ksort( $wpide_spend_tiers );

    foreach ( $wpide_spend_tiers as $min => $off ) {
        if ( $subtotal >= $min ) {
            $current = array( $min, $off );
        } elseif ( null === $next ) {
            $next = array( $min, $off );
        }
    }

    return array( $current, $next );
};

add_action( 'woocommerce_cart_calculate_fees', function ( $cart ) use ( $wpide_spend_tier ) {
    if ( is_admin() && ! wp_doing_ajax() ) {
        return;
    }

    list( $current ) = $wpide_spend_tier( (float) $cart->get_subtotal() );

    if ( $current[1] > 0 ) {
        $cart->add_fee( sprintf( 'Spend discount (%d%%)', $current[1] ), -$cart->get_subtotal() * $current[1] / 100, true );
    }
} );

add_action( 'woocommerce_before_cart', function () use ( $wpide_spend_tier ) {
    $subtotal       = (float) WC()->cart->get_subtotal();
    list( , $next ) = $wpide_spend_tier( $subtotal );

    if ( $next ) {
        wc_print_notice( sprintf( 'Spend %1$s more to save %2$d%% on your order.', wc_price( $next[0] - $subtotal ), $next[1] ), 'notice' );
    }
} );

Notes

Only the highest tier reached applies, and the cart notice disappears once the top tier is reached.

How to add this snippet

  1. Install WPIDE on your WordPress site (it is free) and open Code Snippets.
  2. Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
  3. It is added inactive: review the code and settings, then switch it on.

Have a snippet worth sharing?

Publish it to the library from WPIDE or right here. Sign in with any WordPress site that runs WPIDE, free or Pro. Public snippets are reviewed by the WPIDE team before they appear.

Which site should get this snippet?

Enter the address of your WordPress site. WPIDE opens there in a new tab with the snippet ready to review and save.

Remembered in this browser only, so you are asked once.

Report this snippet

Tell the WPIDE team what is wrong: broken code, something harmful, spam or copied work.