WooCommerce Change User Role After Purchase


If you would like to change the user role only when specific products are in the order, you will need the product IDs ready.

How To Implement This Solution?

Simply copy the pre-coded solution to your active theme’s functions.php or preferably the Code Snippets Plugin.

About this Solution

This snippet will automatically change the role of users who complete a purchase for specific products. Specific to this example, is any one of the three product IDs defined in the code are in the other, the “Customer” role of the buyer will be removed, and a new role added, “Subscriber”. Be careful using this snippet, you don’t want to inadvertently give customers the ability to edit your store! You can make this code work so that all customers, regardless of the products bought, have a new role – that is a case of removing the if statement and foreach loop. Keep in mind, the role is only changed when the order status is set to Complete (this too can be done automatically as shown in this guide).

 * Snippet Name:	WooCommerce Change User Role After Purchase
 * Snippet Author:	ecommercehints.com

add_action( 'woocommerce_order_status_completed', 'ecommercehints_change_user_role_after_purchase' ); // Order Status must be Complete
function ecommercehints_change_user_role_after_purchase($order_id) {
    $order = wc_get_order( $order_id );
    $items = $order->get_items();
    $eligible_product_ids = array( '128', '31', '69' ); // Only change if any one of these product IDs are in the order
    foreach ($items as $item) {
        if ( $order->user_id > 0 && in_array( $item['product_id'], $eligible_product_ids ) ) {
            $user = new WP_User( $order->user_id );
            $user->remove_role( 'customer' ); // The default Customer role is removed 
            $user->add_role( 'subscriber' ); // The new role is added

Snippet Benefits

  • Automatically change the role of a customer when they have bought a product from your WooCommerce store.
WooCommerce Conversion Rate Optimisation (CRO) eBook
100 WooCommerce Conversion Rate Optimisation Tips

Leave a Reply

If you are going to write code in the comments, please wrap it between code tags.

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

Other Recent Guides

Subscribe To Emails

Get exclusive WooCommerce tips that I only share with email subscribers

Join hundreds of other subscribers