Percentage Discount for a User Role
Shows lower prices across the store for customers with a specific role, such as wholesale buyers, without editing each product.
Opens WPIDE on
Code
$wpide_role_pricing = array(
'role' => 'wholesale_customer', // Role that gets the discount.
'percent' => 20, // Discount in percent.
);
$wpide_role_price = function ( $price, $product ) use ( $wpide_role_pricing ) {
if ( '' === $price || ! is_user_logged_in() ) {
return $price;
}
$user = wp_get_current_user();
if ( ! in_array( $wpide_role_pricing['role'], (array) $user->roles, true ) ) {
return $price;
}
return (string) round( (float) $price * ( 100 - $wpide_role_pricing['percent'] ) / 100, wc_get_price_decimals() );
};
foreach ( array( 'woocommerce_product_get_price', 'woocommerce_product_get_regular_price', 'woocommerce_product_get_sale_price', 'woocommerce_product_variation_get_price', 'woocommerce_product_variation_get_regular_price', 'woocommerce_product_variation_get_sale_price', 'woocommerce_variation_prices_price', 'woocommerce_variation_prices_regular_price', 'woocommerce_variation_prices_sale_price' ) as $wpide_hook ) {
add_filter( $wpide_hook, $wpide_role_price, 99, 2 );
}
add_filter( 'woocommerce_get_variation_prices_hash', function ( $hash ) use ( $wpide_role_pricing ) {
$hash[] = is_user_logged_in() && in_array( $wpide_role_pricing['role'], (array) wp_get_current_user()->roles, true ) ? 'wpide-role-' . $wpide_role_pricing['percent'] : 'wpide-role-none';
return $hash;
} );
Notes
Set $role and $percent; the role must already exist (create it with a role editor plugin). Sale prices are discounted too.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.