Bit of a change to @jjj answer above. But I needed it to work with a certain product only if the user had "user_a" role:
function change_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( current_user_can( 'role_a' ) ){
if ( $order->user_id > 0 && $product_id == '248' ) {
update_user_meta( $order->user_id, 'paying_customer', 1 );
$user = new WP_User( $order->user_id );
// Remove role
$user->remove_role( 'role_a' );
// Add role
$user->add_role( 'role_b' );
}
}
else {
return true;
}
}
}
add_action( 'woocommerce_order_status_processing', 'change_role_on_purchase' );