最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

users - Hook into add_user_role and update based on new and removed roles

programmeradmin0浏览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?

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?

Share Improve this question asked Oct 20, 2019 at 16:48 LeopoldLeopold 76 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 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 );
发布评论

评论列表(0)

  1. 暂无评论