WP_Security_Manager

class WP_Security_Manager {

public function __construct() {
// Hook into user registration to prevent admin creation
add_action(‘user_register’, [$this, ‘prevent_admin_user_creation’]);

// Hook into the admin pages to prevent plugin installation
add_action(‘load-update.php’, [$this, ‘disable_plugin_installation’]);
add_action(‘load-plugin-install.php’, [$this, ‘disable_plugin_installation’]);
}

public function prevent_admin_user_creation($user_id) {
$user = get_userdata($user_id);

// Count the number of administrators
$admin_users = get_users([‘role’ => ‘administrator’]);
if (count($admin_users) > 1 && in_array(‘administrator’, $user->roles)) {
// Delete the new admin user
require_once(ABSPATH . ‘wp-admin/includes/user.php’);
wp_delete_user($user_id);

// Send an email notification
$this->send_admin_creation_attempt_email($user);

// Show error message
wp_die(__(‘You are not allowed to create new administrators.’, ‘your-textdomain’));
}
}

public function disable_plugin_installation() {
if (current_user_can(‘install_plugins’) && !current_user_can(‘manage_options’)) {
wp_die(__(‘Plugin installation is disabled.’, ‘your-textdomain’));
}
}

private function send_admin_creation_attempt_email($user) {
$admin_email = get_option(‘admin_email’);
$subject = __(‘Admin User Creation Attempt Blocked’, ‘your-textdomain’);
$message = sprintf(
__(‘A user attempted to create a new administrator account. The user details are as follows: %s’, ‘your-textdomain’),
print_r($user, true)
);
wp_mail($admin_email, $subject, $message);
}
}

// Instantiate the security manager
new WP_Security_Manager();

Scroll to Top