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

How to change role of all users with a specific role to another role?

programmeradmin6浏览0评论

what function can be used to change user role of all users who are currently assigned the role "Customer" to "Editor"?

Basically I need to create a cron job doing this daily. I have figured out the cron job part but need help with how to change roles via function.

what function can be used to change user role of all users who are currently assigned the role "Customer" to "Editor"?

Basically I need to create a cron job doing this daily. I have figured out the cron job part but need help with how to change roles via function.

Share Improve this question edited May 3, 2018 at 5:33 dc09 asked May 3, 2018 at 5:22 dc09dc09 1952 silver badges14 bronze badges 1
  • while the question is on topic, it is very bare. Please add some context regarding the why. As it is, the answer "go to the user admin and change it", is probably the simplest and most accurate one – Mark Kaplun Commented May 3, 2018 at 5:26
Add a comment  | 

1 Answer 1

Reset to default 1

Use the following function:

function wpse_replace_user_role( $from, $to ) {
    $args = array( 'role' => $from );
    $users = new WP_User_Query( $args );
    if ( !empty( $users->get_results() ) ) {
        foreach( $users->get_results() as $user ) {
            $u = new WP_User( $user->ID );
            $u->remove_role( $from );
            $u->add_role( $to );
            unset( $u );
        }
        unset( $users );
    }
}
  • $from - query all users with this role
  • $to - role to be set instead, for each queried user
发布评论

评论列表(0)

  1. 暂无评论