Halloween Sale 15% off Ends in See the plans
PHP

Add a Site Manager Role (No Database Changes)

Adds a "Site Manager" role with everything an editor can do plus managing users and menus, defined in code so nothing is written to the database.

Don’t have WPIDE yet? Install it on your site

Code

$wpide_add_site_manager = function ( $wp_roles ) {
    if ( isset( $wp_roles->roles['site_manager'] ) ) {
        return;
    }

    $editor = $wp_roles->get_role( 'editor' );
    $caps   = array_merge(
        $editor ? $editor->capabilities : array( 'read' => true ),
        array(
            'list_users'         => true,
            'create_users'       => true,
            'edit_users'         => true,
            'delete_users'       => true,
            'promote_users'      => true,
            'edit_theme_options' => true,
        )
    );

    $wp_roles->roles['site_manager']        = array( 'name' => 'Site Manager', 'capabilities' => $caps );
    $wp_roles->role_objects['site_manager'] = new WP_Role( 'site_manager', $caps );
    $wp_roles->role_names['site_manager']   = 'Site Manager';
};

add_action( 'wp_roles_init', $wpide_add_site_manager );

if ( did_action( 'wp_roles_init' ) ) {
    $wpide_add_site_manager( wp_roles() );
}

// Site managers cannot create administrators or change administrator accounts.
add_filter( 'editable_roles', function ( $roles ) {
    if ( ! current_user_can( 'manage_options' ) ) {
        unset( $roles['administrator'] );
    }

    return $roles;
} );

add_filter( 'map_meta_cap', function ( $caps, $cap, $user_id, $args ) {
    if ( in_array( $cap, array( 'edit_user', 'delete_user', 'remove_user', 'promote_user' ), true ) && ! empty( $args[0] ) && (int) $args[0] !== (int) $user_id && user_can( (int) $args[0], 'manage_options' ) && ! user_can( $user_id, 'manage_options' ) ) {
        $caps[] = 'do_not_allow';
    }

    return $caps;
}, 10, 4 );

Notes

Users given this role lose their permissions while the snippet is inactive; reassign them before removing it.

How to add this snippet

  1. Install WPIDE on your WordPress site (it is free) and open Code Snippets.
  2. Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
  3. It is added inactive: review the code and settings, then switch it on.

Have a snippet worth sharing?

Publish it to the library from WPIDE or right here. Sign in with any WordPress site that runs WPIDE, free or Pro. Public snippets are reviewed by the WPIDE team before they appear.

Which site should get this snippet?

Enter the address of your WordPress site. WPIDE opens there in a new tab with the snippet ready to review and save.

Remembered in this browser only, so you are asked once.

Report this snippet

Tell the WPIDE team what is wrong: broken code, something harmful, spam or copied work.