我需要根据添加和删除的每个角色添加用户元。我试图通过挂接add\\u user\\u角色并循环更新用户角色列表来实现这一点,但旧的角色仍然会返回到角色数组中。
因此,如果我转到admin user并取消选中author和check editor,角色循环仍然包括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 );
那么,我如何在角色更改后执行此操作,并提供一个仅反映更改后剩余角色的列表?