Halloween Sale 15% off Ends in See the plans
PHP

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.

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

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

  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.