In woocommerce I am trying to change the user role depending on customer purchased products. I saw the various code and tried them all without being able to make them work.
I have several products to check for different user roles change.
This is my code attempt:
add_action('woocommerce_order_status_completed', 'change_role_on_purchase' );
$products_to_check = array( '5345, 5344,5342' );
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( 'Subscriber' );
$user->add_role( 'Student-Group' );
// Exit the loop
break;
}
}
$products_to_check = array( '5353, 5352,5351,12119' );
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( 'Subscriber' );
$user->add_role( 'Student-11free2' );
// Exit the loop
break;
}
}
$products_to_check = array( '5360, 5359,5358' );
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( 'Subscriber' );
$user->add_role( 'Student-11free3' );
// Exit the loop
break;
}
}
$products_to_check = array( '5363, 5362,5361' );
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( 'Subscriber' );
$user->add_role( 'Student-11regular2' );
// Exit the loop
break;
}
}
But it doesn't work. Any help will be appreciated.