Created
December 5, 2016 18:52
-
-
Save bappi-d-great/fc66706362eed8b3f7eb2a55ca961a15 to your computer and use it in GitHub Desktop.
WPMU M2 Autofill username in registration form
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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