Automatically Add a Role When a Customer Buys a Specific Product

In this step-by-step guide, I will show how to automatically add a WordPress user role when a customer purchases a specific product.

Below, you will find two approaches:

Both ways are pretty good; you can choose whatever suits you best. If you’re not comfortable with the code, you can use the plugin and vice versa.

Now, let’s jump into it.

Use a Plugin to Add a Role to a Customer When a Specific Product is Purchased.

First things first, here is the link to the plugin. You can also install and activate it directly from your WordPress admin dashboard.

Then, visit the WooCommerce > Settings > Products > Assign roles on product purchase page, where you can set your custom conditions.

Here is an example in the screenshot below:

Add role when product purchased WooCommerce
There are two conditions in this screenshot: when either “Product 1” or “Product 2” (or both) is purchased by a customer, then the “Premium customers” role will be automatically added.

Programmatically

The programmatic process of assigning a user role after a product purchase in WooCommerce consists of two steps:

  1. We have to decide on a WooCommerce hook we’re going to use, because there are plenty of them, and each one can be triggered under different conditions
  2. Then we check the order items whether there is a specific product (or products) in the order and do the thing.

Let me treat you with a ready-to-use code snippet, and then I will explain everything to you.

add_action( 'woocommerce_payment_complete', 'rudr_set_role_on_specific_product_purchase' );

function rudr_set_role_on_specific_product_purchase( $order_id ) {

	// get an order object
	$order = wc_get_order( $order_id );
	// if this purchase has been made without creating an account, do nothing
	if( ! $order->user_id ) {
		return;
	}
		
	$items = $order->get_items();
	
	// one or multiple product IDs to check
	$product_ids = array( 5, 10, 32 );

	foreach( $items as $item ) {

		if( in_array( $item[ 'product_id' ], $product_ids ) ) {
			
			$user = new WP_User( $order->user_id );
			// do we need to remove a previous user role? (optional)
			$user->remove_role( 'customer' ); 
			// add role
			$user->add_role( 'editor' );
			break; // exit the loop
			
		}
	}
			
}

In case you still don’t know where to insert the code, please read this.

Now let’s deconstruct this code a little bit:

foreach( $user->roles as $prev_role ) {
	$user->remove_role( $prev_role ); 
}

That’s pretty much it. If you have any questions or maybe suggestions on how I could improve the plugin, feel free to ask in the comments below.

Misha Rudrastyh

Misha Rudrastyh

Hey guys and welcome to my website. For more than 15 years I've been doing my best to share with you some superb WordPress guides and tips for free.

Need some developer help? Contact me

Follow me on X