Many businesses allow their customers to unlock benefits and discounts once a certain spend amount is reached.
Think about a “VIP club“, where members can get an exclusive 20% discount once they reach $1,000 worth of store purchases.
Let’s also say that, when the threshold is reached, you want to promote users from the “customer” role to a custom “VIP customer” role, so that it’s easier to segment your email marketing and overall targeting.
Well, the snippet below will allow you to switch user role once a certain spend is reached. The function will trigger when a customer places an order, so that we can calculate the total spent, and possibly switch their role. Enjoy!
PHP Snippet: Maybe Switch User Role When Customer Spends More Than $$$ (Lifetime)
Note: of course you first need to create your custom user role (‘vip-customer’ in the example below, but you can name it as you wish as long as you change the code accordingly). You can use the free User Role Editor WordPress plugin if you wish.
/**
* @snippet Maybe Switch User Role Upon WooCommerce Order
* @how-to Get CustomizeWoo.com FREE
* @author Rodolfo Melogli
* @compatible WooCommerce 8
* @community https://businessbloomer.com/club/
*/
add_action( 'woocommerce_order_status_changed', 'bbloomer_maybe_trigger_switch_user_role' );
function bbloomer_maybe_trigger_switch_user_role( $order_id ) {
$order = wc_get_order( $order_id );
$user_id = $order->get_user_id();
$order_status = $order->get_status();
$switch_already_done = $order->get_meta( '_bb_role_switched' );
if ( ! $switch_already_done && $order->has_status( wc_get_is_paid_statuses() ) && wc_user_has_role( $user_id, 'customer' ) ) {
bbloomer_customer_maybe_upgrade_to_vip( $user_id );
$order->update_meta_data( '_bb_role_switched', 'true' );
$order->save();
}
}
function bbloomer_customer_maybe_upgrade_to_vip( $user_id ) {
if ( wc_get_customer_total_spent( $user_id ) > 999.99 ) { // THRESHOLD
$user = new WP_User( $user_id );
$user->add_role( 'vip-customer' );
$user->remove_role( 'customer' );
}
}