dpcnm2132 2018-07-31 21:46
浏览 65
已采纳

Wordpress条件添加辅助角色

I need to create a function that works like this one of these:

Is primary user role Subscriber but NOT also any other secondary role? Then add the secondary role "Staff" to the user. So they are Subscriber & Staff.

I suck with conditional PHP. Can anyone give me a clean function?

  • 写回答

1条回答 默认 最新

  • dongque1958 2018-07-31 22:19
    关注

    There are a handful of User Role plugins out there that could help, such as Multiple Roles. I've personally not used it so I can't attest to how well it performs. If you just want a simple function, you will need to make use of the add_role() function on a WP_User object.

    So, get your User Object however you want:

    • If you want to do this to the currently logged in user, use wp_get_current_user().
    • If you want to do this by user ID, you can use get_userdata().
    • If you want to do this by another user field (username, email, etc. note: ID works here too) use get_user_by()

    To run this for any user that's logged in, you can use something like this:

    add_action( 'init', 'add_staff_role_to_subscriber');
    function add_staff_role_to_subscriber(){
        if( is_user_logged_in() ){
            $user = wp_get_current_user();
    
            // If user is a Subscriber with NO other roles
            if( $user->roles[0] == 'subscriber' && ! isset( $user->roles[1] ) ){
                $user->add_role('staff');
            }
        }
    }
    

    What it does is make sure the current user is logged in, and then gets the WP_User object for that user. $user->roles is a single-dimensional array, so you can just make sure that the only role assigned to them is subscriber and that there is no second $role in the array by making sure $user->roles[1] isn't set, or is false.

    Once the staff role is added to the user, the if statement will always be false since $user->roles[1] will be set to staff, or if they already have a secondary role it won't effect them.

    Note, that in your question you have Subscriber capitalized, but roles are lowercase in WordPress, so I made staff lowercase in my code. You may need to make sure the capitalization matches before executing this code.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 组策略中的计算机配置策略无法下发
  • ¥15 机器学习简单问题解决
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)
  • ¥50 mac mini外接显示器 画质字体模糊
  • ¥15 TLS1.2协议通信解密
  • ¥40 图书信息管理系统程序编写