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
break;
}
}
}