Conditionally updating roles in WordPress

I actually want to create an easy function but it doesn’t seem to work.
I want that when a user logs to his account on WordPress to change his role (subscriber -> directory_1) on some condition (easy in this case to test, it should change everytime, but still not working).
Here is my code :

add_action('wp_login', 'update_roles');

function update_roles()
{
   global $wpdb;
   $author = wp_get_current_user();
   if(current_user_can('subscriber'))
   {
       $author->remove_role( 'subscriber' );
       $author->add_role( 'directory_1' );
   }
}

Thanks for the help!

Related posts

Leave a Reply

1 comment

  1. You should be using wp_update_user() to update a user’s role. After you have added a role using add_role(), you can do something like this:

    function custom_update_roles( $user_login, $user ) {
    
        if ( ! empty( $user->roles ) && is_array( $user->roles ) ) {
    
            if ( in_array( "subscriber", $user->roles ) ) {
                $user_id = wp_update_user( array( 'ID' => $user->ID, 'role' => 'directory_1' ) );
    
                if ( is_wp_error( $user_id ) ) {
                    // Error.
                } else {
                    // Success.
                }
            } else {
                // This user is not a subscriber.
            }
        }
    }
    add_action( 'wp_login', 'custom_update_roles', 10, 2 );
    

    Refs: