• The following code if added to your themes functions.php will prevent people from registering to your wordpress site if it contains certain words, in this case “admin”. However it only works for exact match. I want to make it so that it works for partial match. What do I need to edit to achieve this?

    function sozot_validate_username($valid, $username) {
        $forbidden = array('admin');
        $pages = get_pages();
        foreach ($pages as $page) {
            $forbidden[] = $page->post_name;
        }
        if(!$valid || is_user_logged_in() && current_user_can('create_users') ) return $valid;
        $username = strtolower($username);
        if ($valid && strpos( $username, ' ' ) !== false) $valid=false;
        if ($valid && in_array( $username, $forbidden )) $valid=false;
        if ($valid && strlen($username) < 5) $valid=false;
        return $valid;
    }
    add_filter('validate_username', 'sozot_validate_username', 10, 2);
    
    function sozot_registration_errors($errors) {
        if ( isset( $errors->errors['invalid_username'] ) )
            $errors->errors['invalid_username'][0] = __( 'ERROR: Invalid username.', 'sozot' );
        return $errors;
    }
    add_filter('registration_errors', 'sozot_registration_errors');
Viewing 2 replies - 1 through 2 (of 2 total)
  • Tim Nash

    (@tnash)

    Spam hunter

    The in_array is looking to exact match where as you want a partial so you would want to do something like:

    array_filter($forbidden, function($r) use ($username) {
            return ( strpos($r['text'], $username) !== false );
        });

    For more details see https://uk3.php.net/array_filter

    However you might be better off using a regular expression, also it looks like you appear to be also adding the name of pages to your forbidden list which just seems a little weird as they will contain spaces and short words like I or A in which case on a partial match all user names with a or i in the title might get caught.

    So consider just having a stop list, might also be worth searching wp.org plugins as I’m sure there are dozens of plugins with this functionality which you can look at the code.

    Thread Starter Stanfoo

    (@stanfoo)

    Thanks for your reply. I’m a novice at these coding however. Is it possible for you to just give me the new code? With the stop list you suggested so the space problem you mentioned won’t happen.

    Also there is only 1 plugin I’m aware of that does this (called “Restrict Usernames”) it does not work properly.

Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘What is the partial match string?’ is closed to new replies.