When developing an e-commerce website, we often need to provide discounts for specific membership levels—for example, giving members a 20% discount. While WooCommerce doesn’t offer a built-in feature for dynamic pricing based on user roles, we can easily implement this using plugins or custom code.
To achieve this, we need to focus on two key areas: modifying the displayed price of products while browsing and adjusting the price of items within the shopping cart and during checkout.
1. Modifying WooCommerce Product Display Prices
The following code snippet demonstrates how to apply a global 20% discount (0.80 multiplier) for logged-in users with the “customer” role when they browse the shop.
add_filter( 'woocommerce_get_price_html', function ( $price_html, $product ) {
// Only modify prices on the frontend
if ( is_admin() ) return $price_html;
// Skip products without a set price to avoid affecting free items
if ( '' === $product->get_price() ) return $price_html;
// Apply 20% discount if the user has the 'customer' role
if ( wc_current_user_has_role( 'customer' ) ) {
$orig_price = wc_get_price_to_display( $product );
$price_html = wc_price( $orig_price * 0.80 );
}
return $price_html;
}, 9999, 2 );
2. Modifying Prices in the Shopping Cart
Changing the display price isn’t enough; we also need to ensure the discount is applied to the actual transaction. The following code modifies the product price within the cart session. When the user proceeds to checkout, the order total will be calculated based on these adjusted cart prices.
add_action( 'woocommerce_before_calculate_totals', function ( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) ) return;
// Avoid infinite loops by checking action count
if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 ) return;
// Exit if the user is not a 'customer'
if ( ! wc_current_user_has_role( 'customer' ) ) return;
// Iterate through cart items and apply the 20% discount
foreach ( $cart->get_cart() as $cart_item_key => $cart_item ) {
$product = $cart_item['data'];
$price = $product->get_price();
$cart_item['data']->set_price( $price * 0.80 );
}
}, 9999 );
While this code-based approach is efficient for simple logic, more complex dynamic pricing requirements (such as bulk discounts or category-specific rules) can become difficult to manage manually. In those cases, we recommend professional plugins like Dynamic Pricing or Advanced Dynamic Pricing for WooCommerce.
