Automating WooCommerce User Role Upgrades Based on Spending

In a tiered membership or loyalty program, automatically upgrading a user’s level based on their total spending is a powerful way to drive engagement. For example, once a customer spends over $1,000, they could be automatically moved to a “VIP” role, granting them access to exclusive discounts or early product releases. In WooCommerce, we can achieve this seamlessly using the woocommerce_order_status_changed hook.

The Automated Upgrade Logic

First, we’ll create a helper function that checks a user’s cumulative spending. If it exceeds our defined threshold (e.g., $999.99), we’ll add the ‘vip-customer’ role and remove the standard ‘customer’ role.

function wprs_maybe_upgrade_customer_to_vip( $user_id ) {
    // Use built-in WooCommerce function to get lifetime spending
    if ( wc_get_customer_total_spent( $user_id ) > 999.99 ) {
        $user = new WP_User( $user_id );
        $user->add_role( 'vip-customer' );
        $user->remove_role( 'customer' );
    }
}

Triggering the Upgrade

The best time to perform this check is when an order status changes to “Completed” or “Processing” (i.e., when the order is considered paid). We’ll also use sub-meta data to ensure we only attempt the role switch once per order to optimize performance.

add_action( 'woocommerce_order_status_changed', function ( $order_id ) {
    $order = wc_get_order( $order_id );
    $user_id = $order->get_user_id();
    
    // Check if we've already processed a role switch for this specific order
    $already_switched = $order->get_meta( '_wprs_role_switched' );

    if ( ! $already_switched && $order->has_status( wc_get_is_paid_statuses() ) && wc_user_has_role( $user_id, 'customer' ) ) {
        wprs_maybe_upgrade_customer_to_vip( $user_id );

        // Mark this order as processed for role switching
        $order->update_meta_data( '_wprs_role_switched', 'true' );
        $order->save();
    }
} );

Handling Refunds

To maintain the integrity of your VIP program, you should also consider what happens when an order is refunded. You can hook into woocommerce_order_refunded to recalculate the user’s total spending and demote them if they fall below the threshold. This ensures that your premium benefits are reserved for your most active and valuable customers.

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *