WC Series : Customize the product price by user role

Sometimes, you need to override the default product price based on user role. You may use different unit price depend on customer role (e.g vip-member, reseller ). This tutorial will guide you the whole process to override the price

Overriding get_price() function

Before we go into the the source code, let us understand the background of what we are doing. Basically, in any part of woocommerce template, object or functions, it calls get_price() function to get the product price value.

So, we will add a filter function to control the return value from this get_price() function. This function is located at

includes/abstracts/abstract-wc-product.php

The function is abstracted from get_prop() method in WC Product class

add_filter('get_price', 'mukhlis_override_price', 99, $product);
function mukhlis_override_price($price){
    /* check the user role */
    $user = wp_get_current_user();
    if ( in_array( 'reseller', (array) $user->roles ) ) {
       /* The user has the "reseller" role */
       $price = $price*0.85; /* reseller will get 15% discount */
    }
    return $price;

}

This code will check the user role by getting current user and check it’s role. If the role is reseller, then the price automatically discounted 15%. Please note that the reseller role might be customized user role, you might use this plugin to add customized user role.

Explore the possibilities

With the above example, basically you can extend the function with your custom logic and conditions. Besides checking the user role, you also can check product type or category to vary the price. Or you can even randomly give discount to lucky customer that viewing your product at particular date and time or returning visitor. It just about working on conditional logic and creteria.

From the hook, we get two parameters which is original price and WC Product object. Besides given parameters, we also can access global variables such as current user, cart items. Also other objects or variables such as $_SERVER, $_POST, $_GET, $_COOKIES & etc.

Conclusion

With little imagination, you can take this price overriding method to next level with your custom logics and conditions. It was a small hook function with powerful output.

Hope you can try this method and share your experience.


Posted

in

by

Tags: