WooCommerce price based on user role

One of my clients needed different product prices for their users based on their role. His website included a user role for resellers who have to see lower prices than default customers.

To modify the price based on the user role I needed 2 things to know:

  1. How to check the current user’s role?
  2. What are the WooCommerce price filter hooks to hook into?

Check current user role

To know whether the current logged in user has the specific “reseller” role I created a simple function that checks it for you. I wrote a post called “WordPress user has role” where I explain how it works.

WooCommerce price filter hooks

To modify the price WooCommerce gives 4 different hooks to hook into based on your needs.

  1. woocommerce_product_get_price To filter the product price.
  2. woocommerce_product_variation_get_price To filter the variation product price.
  3. woocommerce_product_get_regular_price To filter the regular product price.
  4. woocommerce_product_get_sale_price To filter the product sale price.

When you for example do not want to reduce your sale price you simply don’t hook into the woocommerce_product_get_sale_price filter.

Now that you know all the filter hooks let me show you how the filter function itself looks like.

/**
 * Filter the price based on user role
 */
function th_reseller_price( $price ) {

   if ( ! is_user_logged_in() )
      return $price;

   // Function which checks if logged in user is reseller
   if ( th_has_role( 'reseller' ) ) {
      $reseller_percentage = 0.67;
      $price = $price * $reseller_percentage;
   }
   return $price;

}
add_filter( 'woocommerce_product_get_price', 'th_reseller_price', 10, 2 );
add_filter( 'woocommerce_product_variation_get_price', 'th_reseller_price', 10, 2 );
add_filter( 'woocommerce_product_get_regular_price', 'th_reseller_price', 10, 2 );
add_filter( 'woocommerce_product_get_sale_price', 'th_reseller_price', 10, 2 );

The function first checks whether a user is logged in. Then it uses my custom function to check whether the current user has a role of “reseller”. If this is the case it multiplies the price variable by a percentage and returns a reduced price.

Robbert Vermeulen

Need help from a WordPress expert?

I would love to hear about your project and how I can help you achieve your goals