Add secondary role to the new registered user

User Role Editor allows to assign multiple roles per user. What if you need that new registered users get multiple roles by default just after their registration?
For the time being you may do it with this piece of code included into your active theme functions.php file:

add_action( 'user_register', 'add_secondary_role', 10, 1 );

function add_secondary_role( $user_id ) {
    
    $user = get_user_by('id', $user_id);
    $user->add_role('screen_reader');

}

The code above adds to every new registered user the secondary role ‘screen_reader’ in addition to the default role ‘subscriber’ added by WordPress itself.

It works, but what will be when you switch to the other theme? Yes, it will stop working until you will not duplicate the code at new active theme functions.php file. If you change blog theme periodically or if you work with multi-site WordPress installation you may need more universal decision. With “multi-site” in mind we should use modified code:

if (is_multisite()) {
    add_action( 'wpmu_activate_user', 'add_secondary_role', 10, 1 );
} else {
    add_action( 'user_register', 'add_secondary_role', 10, 1 );
}
 
function add_secondary_role( $user_id ) {
 
    $user = get_user_by('id', $user_id);
    $user->add_role('screen_reader');
 
}

It works universally now as for single-site, as for multi-site WordPress installations. In order to not insert this code into every theme from themes poole which your subsites use, we may apply it another way.

WordPress has a convenient feature called “must-use” plugins. How does it work?

Create folder wp-content/mu-plugins, place there file with ‘.php’ extension and some PHP code inside. That’s it. This code will be executed by WordPress for every page request. There is no need to activate it. And it can not be deactivated with WordPress administrator interface.
So, create PHP file, for example must-use.php, insert code you see below into that file:

if (is_multisite()) {
    add_action( 'wpmu_activate_user', 'add_secondary_role', 10, 1 );
} else {
    add_action( 'user_register', 'add_secondary_role', 10, 1 );
}
 
function add_secondary_role( $user_id ) {
 
    $user = get_user_by('id', $user_id);
    $user->add_role('screen_reader');
 
}

Do not forget to add he required ‘<?php’ tag at the 1st line. Put must-use.php file into wp-content/mu-plugins folder. You did it.

P.S. I included this feature (multiple default roles) to my development plan. So it will appear as an option at the “User Role Editor Pro” soon.

Share