I think there's a few options how you can do this, depending on at which point you want to do the username validation.
1) Validate username (and email) after (default) registration form has been submitted and before the user is created
Error messages are shown on the registration page.
function my_prefix_registration_errors( $errors, $sanitized_user_login, $user_email ) {
if ( ! is_valid_username( $sanitized_user_login ) ) {
$errors->add( 'invalid_username', __( '<strong>ERROR</strong>: Invalid username.', 'my_textdomain' ) );
}
if ( ! is_valid_email( $user_email ) ) {
$errors->add( 'invalid_email', __( '<strong>ERROR</strong>: Invalid email.', 'my_textdomain' ) );
}
return $error;
}
add_filter( 'registration_errors', 'my_prefix_registration_errors', 10, 3 );
2) Validate username when the user is being created with wp_insert_user()
// step 1, validate username
function my_prefix_pre_user_login( $sanitized_user_login ) {
if ( ! is_valid_username( $sanitized_user_login ) ) {
$sanitized_user_login = 'illegal_username';
}
return $sanitized_user_login;
}
add_filter( 'pre_user_login', 'my_prefix_pre_user_login' );
// step 2, add blocked usernames. If username is invalid after step 1, it will trigger "invalid_username" WP_Error with this filter thus blocking the registration
function my_prefix_illegal_user_logins() {
return array('illegal_username');
}
add_filter( 'illegal_user_logins', 'my_prefix_illegal_user_logins' );
3) Allow all registrations, but change user role, if illegal username after new registration
function my_prefix_register_new_user( $user_id ) {
$user = get_user_by( 'ID', $user_id );
if ( ! is_valid_username( $user->user_login ) ) {
$user->set_role('invalid_registration');
}
}
add_filter( 'register_new_user', 'my_prefix_register_new_user' );
4) Building upon T.Toduas answer regardin multisite user activation.
Activation without the use of $GLOBALS
.
function t_toduas_user_register_function($user_id){
// get user data
$user_info = get_userdata($user_id);
if ( is_valid_username( $user_info->login ) ) {
$res = get_activation( $user_info->login );
if ( !empty( $res ) ) {
wpmu_activate_signup( $res->activation_key );
}
}
}
add_action('user_register','t_toduas_user_register_function');
Helper functions for the examples above
function get_allowed_usernames() {
return array(
'donald',
'goofy'
'mickey'
);
}
function get_valid_domain() {
return 'example.com';
}
function is_valid_username( $username ) {
return in_array( $username, get_allowed_usernames() );
}
// crude email validation
function is_valid_email( $email ) {
if ( is_email( $email ) ) {
return false;
}
$email_pieces = explode( '@', $email );
return in_array( get_valid_domain(), $email_pieces );
}
function get_activation( $login ) {
global $wpdb;
return $wpdb->query($wpdb->prepare("SELECT activation_key from {$wpdb->signups} WHERE user_login = %s)", $login));
}