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:
- We have to decide about the hook, when exactly we are going to do a role switching, because there are plenty of them.
- 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:
- I decided to use
woocommerce_payment_complete
hook to make sure that the payment has actually been made, in some tutorial they usewoocommerce_order_status_{$status}
, not sure whether it is a correct way, more about it here. - In case you still don’t know where to insert the code, please read this.
- I am also using
$order->get_items()
method to get all the products in the order, more about it in a separate tutorial. - On lines
8-10
we check whether this purchase has been made by an actual user or by someone without creating an account. If you don’t want anyone without an account to make purchases on your website, you can turn off it in WooCommerce settings:

- On line
15
specify one or multiple product IDs which should be in the order in order to make the role change. - If you would like to remove a previous customer role, specify it on line
23
, the new role (or multiple roles) – on line25
. If you don’t know what previous customer role was, you can modify the code a little bit:
foreach( $user->roles as $prev_role ) {
$user->remove_role( $prev_role );
}

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