0

I need to add user meta based on each role added and removed. I tried to achieve this by hooking into add_user_role and looping through and updated list of user roles but the old ones are still returned in the array of roles.

So if I were to go to admin user and uncheck author and check editor, the loop of roles is still including author

function update_user_department( $user_id ) {
    $user_meta = get_userdata($user_id);
    $user_roles = $user_meta->roles; // returning role that was unchecked with new role checked. Should only return roles that were checked when role was updated
    $ranks = get_ranks_expanded();
    $newDepartments = array();
    foreach ($user_roles as $user_role) {
        $department = $ranks[$user_role]["department"];
        if (!in_array($department, $newDepartments)) {
            $newDepartments[] = $department;
        }   
    }
    update_user_meta($user_id, "departments", $newDepartments);
}
add_action( 'add_user_role', 'update_user_department', 10 );

So how can I execute this after role change with a list of reflecting only the roles left after the change?

1 Answer 1

0

I ended up just adding a second hook to remove_user_role using the same function

add_action( 'remove_user_role', 'update_user_department', 10, 1 );

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.