Code to add into theme functions for renaming user roles

Is there code that I can add into the functions.php file in a theme to change role names. I have a plugin that does it right now, but would prefer to run it through the theme functions if possible. I found the following code, but when adding it into the themes functions.php file it doesn't seem to work:

function change_role_name() {
    global $wp_roles;

    if ( ! isset( $wp_roles ) )
        $wp_roles = new WP_Roles();

    //You can list all currently available roles like this...
    //$roles = $wp_roles->get_names();
    //print_r($roles);

    //You can replace "administrator" with any other role "editor", "author", "contributor" or "subscriber"...
    $wp_roles->roles['subscriber']['name'] = 'Vendor';
    $wp_roles->role_names['subscriber'] = 'Vendor';
     $wp_roles->roles['contributor']['name'] = 'Contractor';
    $wp_roles->role_names['contributor'] = 'Contractor';
    $wp_roles->roles['author']['name'] = 'Employee';
    $wp_roles->role_names['author'] = 'Employee';
    $wp_roles->roles['editor']['name'] = 'Management';
    $wp_roles->role_names['editor'] = 'Management';
    $wp_roles->roles['administrator']['name'] = 'Administrator';
    $wp_roles->role_names['administrator'] = 'Administrator';
}
add_action('init', 'change_role_name');
  • Ash

    Hello @Jason

    I hope you are well today and thanks for asking the question.

    I have tried similar version of your code and it worked perfectly fine for me.

    function change_role_name() {
        global $wp_roles;
    
        if ( ! isset( $wp_roles ) )
            $wp_roles = new WP_Roles();
    
        $wp_roles->roles['PEIadmin']['name'] = 'PEI';
        $wp_roles->role_names['PEIadmin'] = 'PEI';
    
        $wp_roles->roles['administrator']['name'] = 'Owner';
        $wp_roles->role_names['administrator'] = 'Owner';
    }
    add_action('init', 'change_role_name');

    Make sure you have put the code in your active theme's functions.php. Otherwise mu-plugins is the best solution. To use mu-plugins, go to /wp-content/ and find the folder with name 'mu-plugins'. If there is no folder in that name, then create a folder, name it 'mu-plugins', create a file inside that, give any name you like and paste the code in their. You don't need to activate that plugin. Mu-plugins means must use plugins, so it will be activated automatically always.

Thank NAME, for their help.

Let NAME know exactly why they deserved these points.

Gift a custom amount of points.