Skip to content

Instantly share code, notes, and snippets.

@ghwoodard
Created February 1, 2024 22:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ghwoodard/11d3242497e1e1ae2a892983755249d0 to your computer and use it in GitHub Desktop.
Save ghwoodard/11d3242497e1e1ae2a892983755249d0 to your computer and use it in GitHub Desktop.
Create a custom user role in WordPress and remove admin pages that don't have the user role
<?php
/*
You want to add this code to the functions.php file or, ideally, to a new plugin. Best for when you need to provide admin
access to a website but don't want admins having access to certain pages that will break or mess up the website.
*/
function create_support_team_role() {
// Add a new role called "Support Team"
add_role( 'support_team', 'Support Team' );
// Get the administrator role object
$admin_role = get_role( 'administrator' );
// Make sure the administrator role exists
if ( ! empty( $admin_role ) ) {
// Get all capabilities of the administrator role
$admin_capabilities = $admin_role->capabilities;
// Add the custom capability "support_team" to the "Support Team" role
$support_team_role = get_role( 'support_team' );
$support_team_role->add_cap( 'support_team' );
// Duplicate the same capabilities as the administrator role to the "Support Team" role
foreach ( $admin_capabilities as $capability => $value ) {
$support_team_role->add_cap( $capability );
}
}
}
add_action( 'init', 'create_support_team_role' );
function remove_admin_pages_for_non_support_team() {
// Check if the current user is not a Support Team member
if ( ! current_user_can( 'support_team' ) ) {
// Remove the "Posts" menu page
remove_menu_page( 'edit.php' );
// Remove the "Pages" menu page
remove_menu_page( 'edit.php?post_type=page' );
// Remove the "Comments" menu page
remove_menu_page( 'edit-comments.php' );
// Remove the "Appearance" submenu page
remove_submenu_page( 'themes.php', 'themes.php' );
// Remove the "Plugins" submenu page
remove_submenu_page( 'plugins.php', 'plugins.php' );
// Remove the "Users" submenu page
remove_submenu_page( 'users.php', 'users.php' );
// Remove the "Tools" submenu page
remove_submenu_page( 'tools.php', 'tools.php' );
// Remove the "Settings" submenu page
remove_submenu_page( 'options-general.php', 'options-general.php' );
}
}
add_action( 'admin_menu', 'remove_admin_pages_for_non_support_team' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment