Set a Customer Role after Purchasing a Specific Product

This whole process of changing a user role after making a purchase in WooCommerce actually consists of two steps:

  1. We have to decide about the hook, when exactly we are going to do a role switching, because there are plenty of them.
  2. Check the order if there is a specific product (or products) 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
			
		}
	}
			
}

Now let’s deconstruct this code a little bit:

WooCommerce allow customers without an account create orders
foreach( $user->roles as $prev_role ) {
	$user->remove_role( $prev_role ); 
}
Misha Rudrastyh

Misha Rudrastyh

Hey guys and welcome to my website. For more than 10 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