Skip to content

Instantly share code, notes, and snippets.

@bappi-d-great
Created December 5, 2016 18:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bappi-d-great/fc66706362eed8b3f7eb2a55ca961a15 to your computer and use it in GitHub Desktop.
Save bappi-d-great/fc66706362eed8b3f7eb2a55ca961a15 to your computer and use it in GitHub Desktop.
WPMU M2 Autofill username in registration form
<?php
add_action( 'wp_footer', function() {
if( 'membership_signup' == $_POST['action'] )
{
$membership_id = $_POST['membership_id'];
$membership = MS_Factory::load( 'MS_Model_Membership', intval( $membership_id ) );
$prefix = str_replace( ' ', '_', strtolower( $membership->name ) ) . '_';
$username = get_unique_username( $prefix );
?>
<script type="text/javascript">
jQuery( function($) {
$( '#username' ).val( '<?php echo $username ?>' ).attr( 'readonly', 'readonly' );
} );
</script>
<?php
}
} );
function get_unique_username( $prefix )
{
$username = $prefix . get_random_string();
if( username_exists( $username ) )
{
return get_unique_username( $prefix );
}
else
{
return $username;
}
}
function get_random_string( $length = 5 )
{
$characters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$charactersLength = strlen( $characters );
$randomString = '';
for ( $i = 0; $i < $length; $i++ )
{
$randomString .= $characters[rand( 0, $charactersLength - 1 )];
}
return strtolower( $randomString );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment