← Back to notes
snippet 1 min read PHP 7.4+ WP 5.8+

Programmatically Apply an Auto-Discount Based on Cart Item Count or User Role

Apply a WooCommerce cart discount automatically when a customer buys enough items or belongs to a specific WordPress role.

Updated Aug 20, 2026 #woocommerce #discounts #cart #php #snippet

WooCommerce coupons are useful for customer-facing promotions, but some discounts should happen automatically. The following snippet applies a 10% discount when the cart contains at least five items, or when the logged-in customer has the wholesale_customer role.

Add it to a child theme’s functions.php file or a code snippets plugin. Change the thresholds, role, and discount amount to match the store’s pricing rules.

The snippet

functions.php
add_action( 'woocommerce_cart_calculate_fees', function( $cart ) {
// Never change totals in the admin or before WooCommerce has a cart.
if ( is_admin() && ! defined( 'DOING_AJAX' ) ) {
return;
}
if ( ! $cart || $cart->is_empty() ) {
return;
}
$item_count = $cart->get_cart_contents_count();
$user = wp_get_current_user();
$is_wholesale = in_array( 'wholesale_customer', (array) $user->roles, true );
if ( $item_count < 5 && ! $is_wholesale ) {
return;
}
// Apply the percentage to products only, before shipping and tax.
$discount_base = (float) $cart->get_cart_contents_total();
$discount = round( $discount_base * 0.10, wc_get_price_decimals() );
if ( $discount > 0 ) {
$label = $is_wholesale
? __( 'Wholesale customer discount', 'my-site' )
: __( '5+ item discount', 'my-site' );
$cart->add_fee( $label, -$discount, false );
}
}, 20 );

Item count versus quantity

get_cart_contents_count() counts quantities. Five units of one product satisfy the rule. If the promotion should require five distinct line items instead, use count( $cart->get_cart() ) and adjust the condition.

The example uses get_cart_contents_total(), which is the product subtotal after item discounts and before fees. That means the discount is not calculated from shipping or other fees. The final false argument in add_fee() marks the fee as non-taxable; set it to true only after confirming the tax treatment with your accountant.

Avoid duplicate discounts

Do not also apply the same discount through a coupon, a product sale price, and this fee. WooCommerce can recalculate fees several times during checkout, but the hook runs from the current cart state, so it does not permanently stack the fee. For mutually exclusive rules, use if/elseif instead of two independent conditions.

The WooCommerce cart fees code reference documents the fee API used here. Pair this rule with shipping-method filtering when a discount also changes which delivery options customers should see.