WordPress

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.

Example:

<?php
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.
Rahul Prajapat

I’m Rahul Prajapat. I’m a WordPress developer and Author at TheCodeHubs. I have good skill of Html, CSS, JQuery, SQL, Web API, PSD to HTML/PSD to WordPress, WordPress Theme/Plugin Customization, create or modify short code, customize visual composer short code or integrate new short code with visual composer, can create custom metabox for any post type in WordPress admin.

Recent Posts

Testing hk

Testing

2 years ago

Create and Used PIPE in angular

In this article, we have to show Create and Used PIPE in angular

2 years ago

Operation

Testing

2 years ago

Create and Used PIPE in angular

In this article, we have to show Create and Used PIPE in angular

2 years ago

Create and Used PIPE in angular

In this article, we have to show Create and Used PIPE in angular

2 years ago

TETS NEW

test

3 years ago