The below function provides a feature to change the user’s role in the purchase of a product in WooCommerce. The example function will change the existing ‘Subscriber’ to the role of ‘Customer’.
function change_users_role_on_purchase( $order_id ) {
$order = new WC_Order( $order_id );
$items = $order->get_items();
foreach ( $items as $item ) {
$product_name = $item['name'];
$product_id = $item['product_id'];
$product_variation_id = $item['variation_id'];
if ( $order->user_id > 0 && $product_id == '222' ) {
update_user_meta( $order->user_id, 'paying_customer', 1 );
$user = new WP_User( $order->user_id );
// Remove role
$user->remove_role( 'subscriber' );
// Add new role
$user->add_role( 'customer' );
}
}
}
add_action( 'woocommerce_order_status_processing', 'change_users_role_on_purchase' );
Leave a Comment