Some months ago I talked about how to add a checkout field only for a specific user role with WooCommerce.
Today I’ll show you how to change the user role after purchasing a specific product.
Open your functions.php file in wp-content/themes/your-child-theme-name/ and add this code at the end of the file:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
add_action( 'woocommerce_order_status_completed', 'change_role_on_purchase' ); | |
function change_role_on_purchase( $order_id ) { | |
$order = wc_get_order( $order_id ); | |
$items = $order->get_items(); | |
$products_to_check = array( '1', '2', '3' ); | |
foreach ( $items as $item ) { | |
if ( $order->user_id > 0 && in_array( $item['product_id'], $products_to_check ) ) { | |
$user = new WP_User( $order->user_id ); | |
// Change role | |
$user->remove_role( 'customer' ); | |
$user->add_role( 'new-role' ); | |
// Exit the loop | |
break; | |
} | |
} | |
} |
Note the code on line 6. It is a list of products to check, which means that the custom script will check if one of the products purchased by the customer is in that list. If yes, the user role will change to what you define on line 14.
Line 13 removes the customer’s old role, by default it’s Customer when they buy from you, but it could be different. If you want to remove more than one role, just duplicate the line and change the role slug.
Note: If you defined multiple role switch and the customer purchased more products that will change their role, only the first one found will switch their role.
The original code is by troydean.
Leave a Reply