I've been looking and looking for a solution for my problem but i have been unable to find anything.
I have found a plugin that allow me to restrict certain usernames, I found even a function but there is nothing that allows me to restrict partially matching usernames, there is nothing to prevent users to register under names like "joeadmin" or "seanadmin" and etc.
Is there anything that can be done to prevent users to register anything that contain "admin" and other prohibited words?
I've been looking and looking for a solution for my problem but i have been unable to find anything.
I have found a plugin that allow me to restrict certain usernames, I found even a function but there is nothing that allows me to restrict partially matching usernames, there is nothing to prevent users to register under names like "joeadmin" or "seanadmin" and etc.
Is there anything that can be done to prevent users to register anything that contain "admin" and other prohibited words?
There's a validate_username
filter hook that is used by validate_user()
which is in turn used by register_new_user()
.
So you can disallow usernames containing admin
or other prohibited terms:
add_filter( 'validate_username', 'wpse257667_check_username', 10, 2 );
function wpse257667_check_username( $valid, $username ) {
// This array can grow as large as needed.
$disallowed = array( 'admin', 'other_disallowed_string' );
foreach( $disallowed as $string ) {
// If any disallowed string is in the username,
// mark $valid as false.
if ( $valid && false !== strpos( $username, $string ) ) {
$valid = false;
}
}
return $valid;
}
You can add this code to your theme's functions.php
file or (preferably) make it a plugin.
validate_username
filter hookvalidate_user()
register_new_user()
@pat-j beat me to it by a minute, but I'll elaborate that you can use a reg ex as well:
add_filter( 'validate_username', 'wpse257667_check_username', 10, 2 );
function wpse257667_check_username( $valid, $username ) {
if($valid){
$matches = null;
$returnValue = preg_match('/(admin)/i', $username, $matches);
return empty($matches) ? true : false;
}
}