I have noticed that the code our friend shares has an error. Add the prefix twice.
I share other code with this error resolved.
<?php
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 = str_replace( "https://wordpress.stackexchange.com/", '', get_blog_details()->path );
//error_log($sanitized_path);
if ( $sanitized_path != '') {
if(false === stripos($username, $sanitized_path)) {
return $sanitized_path . '-' . $username;
} else {
return $username;
}
} else {
$domain_parts = explode( '.', $blog_details->domain );
if ( is_array( $domain_parts ) ) {
$sanitized_subdomain = sanitize_user( $domain_parts[0], true );
//error_log($sanitized_subdomain);
if ( $sanitized_subdomain != '' ) {
if(false === stripos($username, $sanitized_subdomain)) {
return $sanitized_subdomain . '-' . $username;
} else {
return $username;
}
}
}
}
}
return $username;
}