Programmatically changing role information; editing role name and deleting

There’s a whole host of functions specifically for this purpose;

http://codex.wordpress.org/Function_Reference#User_and_Author_Functions

Of particular interest (but not limited to) are,

add_cap
add_role
get_role
map_meta_cap
remove_cap
remove_role

As well as numerous other user related functions that will allow you to verify/validate their authority based upon your use-case scenario and so on.

Looking in wp-includes/capabilities.php you we can see that the role_names are held in an array, therefore something to the effect of,

add_action('init', 'update_role_name');
function update_role_name(){
    global $wp_roles;
    $wp_roles->roles['subscriber']['name'] = 'member'; 
    $wp_roles->role_names['subscriber'] = 'member'; 
}

Might need a little tweaking as that’s untested.

Edit:

I just found this: is-there-way-to-rename-user-role-name-without-plugin – check it out. Virtually identical to what I am suggesting but with the exception of instantiating the class and checking that the variable $wp_roles is actually defined/set. I’ll assume that it works on the basis that its marked correctly but naturally please test this to confirm.

But in a similar fashion looking at the following which is taken directly from core installation file wp-includes/capabilities.php line 133,

/**
 * Add role name with capabilities to list.
 *
 * Updates the list of roles, if the role doesn't already exist.
 *
 * The capabilities are defined in the following format `array( 'read' => true );`
 * To explicitly deny a role a capability you set the value for that capability to false.
 *
 * @since 2.0.0
 * @access public
 *
 * @param string $role Role name.
 * @param string $display_name Role display name.
 * @param array $capabilities List of role capabilities in the above format.
 * @return null|WP_Role WP_Role object if role is added, null if already exists.
 */
function add_role( $role, $display_name, $capabilities = array() ) {
    if ( isset( $this->roles[$role] ) )
        return;

    $this->roles[$role] = array(
        'name' => $display_name,
        'capabilities' => $capabilities
        );
    if ( $this->use_db )
        update_option( $this->role_key, $this->roles );
    $this->role_objects[$role] = new WP_Role( $role, $capabilities );
    $this->role_names[$role] = $display_name;
    return $this->role_objects[$role];
}

…we can see,

Updates the list of roles, if the role doesn’t already exist.

add_role( $role, $display_name, $capabilities = array() ) 

…therefore updating the $display_name argument of an existing role will have the same desired effect without actually modifying the role itself so as to preserve its users associated with the role.

Leave a Comment