0

I have a multisite network, where the admins of each site are able to add users to their site. My problem is that if they select the same username it will not work.

So I am thinking if it is possible to save the Username field with a prefix. Say the admin adds a user called johndoe to a site called mysite then the user should be saved as mysite-johndoe. Would this be possible to achieve?

I am talking about the Users->Add New User in the backend.

Hope there is a way to do this! Either with PHP or jQuery?

  • I think you're overlooking the built-in solution. Instead of "add new user" you can "add existing user" so the same person can log into more than one of the sites. – WebElaine Oct 25 '18 at 21:35
0

I am not sure that they would like that prefix, maybe they would prefer to come up with a new username that is not used. But here, I made it how you wanted. It takes either the path of the site or the first part of the subdomain, so it works with both types of multisite. It affects users created by users that are not super administrators.

add_filter( 'pre_user_login', 'sneakily_add_prefix_to_username' );

function sneakily_add_prefix_to_username( $username ) {
    if ( ! current_user_can( 'manage_network' ) ) {
        $blog_id = get_current_blog_id();
        $blog_details = get_blog_details( $blog_id );
        $sanitized_path = sanitize_user( $blog_details->path, true );
        if ( $sanitized_path != '' ) {
            return $sanitized_path . '-' . $username;
        } else {
            $domain_parts = explode( '.', $blog_details->domain );
            if ( is_array( $domain_parts ) ) {
                $sanitized_subdomain = sanitize_user( $domain_parts[0], true );
                if ( $sanitized_subdomain != '' ) {
                    return $sanitized_subdomain . '-' . $username;
                }
            }
        }
    }
    return $username;
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.