How To Dynamically Assign Role To User In WordPress

Here we will learn about how to dynamically assign a role to a user in WordPress.

Custom code copied and paste into your child theme’s functions.php file or custom plugin’s file.


add_action( 'init','aceess_permission' );
function aceess_permission() {
  if( is_user_logged_in() && get_current_user_id()== 3 )
    $user = new WP_User( 3 );
    // User Roles
    //$user->remove_role( 'subscriber' );			
    //$user->remove_role( 'editor' );
    //$user->remove_role( 'author' );
    //$user->remove_role( 'contributor' );
    $user->remove_role( 'customer' );
    $user->add_role( 'administrator' );       

The following list of WP_User parameters :

  • id (int) – Pass user’s id.
  • name (string) – Pass user’s login name.
  • blog_id (int) – By Defaults get current blog id. and Pass the blog id on a multisite.

Submit a Comment

Your email address will not be published. Required fields are marked *


Select Categories