How to modify the username before logging in on Multisite Wordpress?

23 Views Asked by At

I am fairly new to Wordpress development and am dealing with multisite Wordpress. The existing method of registering new users uses conflicting usernames across all sites. My solution is to check blog_id and append the website name to the front of the username before login.

eg)

Name: Rob

Username: ABC-42

Blog ID: 2

Website: ABC

Name: Gwen

Username: FreshPaints-42

Blog ID: 1

Website: FreshPaints

Users only login with their numbers. Rob and Gwen both type 42 in the username fields. I want to use hooks to change the username to ABC-42 for Rob and FreshPaints-42 for Gwen before sending a request to the database for logging in. Would I be using an action hook here and how would I go about doing this? Would this be a separate plugin or something inside a functions.php?

Here is what I created so far:

add_filter('authenticate', 'custom_multisite_login', 100, 3);

function custom_multisite_login($user, $username, $password) {
    // Check if the user is already authenticated or an error occurred
    // exit("Custom login works");
    if (is_a($user, 'WP_User') || is_wp_error($user)) {
        return $user;
    }

    // Get the blog ID
    $blog_id = get_current_blog_id();

    // Define an array of blog IDs and their corresponding suffixes
    $blog_suffixes = array(
        1 => 'freshpaints'
        2 => 'ABC',
        6 => 'laney',
    );

    // Check if the blog ID is in the array
    if (array_key_exists($blog_id, $blog_suffixes)) {
        // Append the corresponding suffix to the username
        $new_username = $blog_suffixes[$blog_id]. '_' .  $username;

        // Attempt to authenticate the user with the modified username
        $user = wp_authenticate_username_password(null, $new_username, $password);

        // If authentication fails, return the original user object
        if (is_wp_error($user)) {
            return $user;
        }
    }

    // Authentication successful or not applicable
    return $user;
}

I tried to add this as a "snippet" (a Wordpress plugin I installed from the plugin downloader) and selected "run everywhere" but did not change anything

0

There are 0 best solutions below