In some of the projects that I'm working there are multiple administrator accounts which means that many people can install plugins and this can cause some serious security problems. In the mean time these people must have administrator accounts, because they need to have the rights in order to work so I use this function to limit the installation of plugins to only one admin account.
```php
function restrict_plugin_installation( $allcaps, $cap, $args ) {
// Define the allowed admin username or user ID
$allowed_admin_username = '
[email protected]'; // Change this to the specific admin username
$allowed_admin_user_id = 1; // Change this to the specific admin user ID
// Get the current user's data
$current_user = wp_get_current_user();
// Check if the current user is the allowed admin
if ( $current_user->user_login === $allowed_admin_username || $current_user->ID === $allowed_admin_user_id ) {
return $allcaps; // Allow all actions for the allowed admin
}
// List of plugin-related capabilities to restrict
$restricted_caps = ['install_plugins', 'upload_plugins', 'delete_plugins', 'activate_plugins'];
// Loop through the restricted capabilities and disable them
foreach ( $restricted_caps as $restricted_cap ) {
if ( isset( $allcaps[$restricted_cap] ) ) {
$allcaps[$restricted_cap] = false; // Disallow the action
}
}
// Allow viewing the plugins list by ensuring 'activate_plugins' is not completely removed,
// but restricted from making any changes. This keeps the Plugins menu item visible.
if ( isset( $allcaps['activate_plugins'] ) ) {
$allcaps['activate_plugins'] = true;
}
return $allcaps;
}
// Hook into the user_has_cap filter to restrict capabilities
add_filter( 'user_has_cap', 'restrict_plugin_installation', 10, 3 );
```