Skip to content

Instantly share code, notes, and snippets.

@Kennyboy7
Last active August 9, 2021 19:15
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 Kennyboy7/4f4e740519a05b32b11888ddf4c030d0 to your computer and use it in GitHub Desktop.
Save Kennyboy7/4f4e740519a05b32b11888ddf4c030d0 to your computer and use it in GitHub Desktop.
GravityForms autocreate preformatted Username
<?
// Set up a GF and use a name field, this use the first and last name to create intials as part of the username
// Add this to your functions.php
// This is preformatted to produce a username that is pk_usersinitials_3 digit random number
// The username is created when the form is submitted
/ Change 3 in gform_username_3 to your form id number.
add_filter( 'gform_username_3', 'auto_username', 10, 4 );
function auto_username( $username, $feed, $form, $entry ) {
GFCommon::log_debug( __METHOD__ . '(): running.' );
// Update 2.3 and 2.6 with the id numbers of your Name field inputs. e.g. If your Name field has id 1 the inputs would be 1.3 and 1.6
//Gets the values from the first and last name fields
$firstName = ucwords( rgar( $entry, '1.3' ));
$lastName = ucwords( rgar( $entry, '1.6' ));
// Convert the names to intials
$firstChar = substr($firstName, 0, 1);
$secondChar = substr($lastName, 0, 1);
// Generates a random 3 digit number to add to the end
$randomNum = substr(str_shuffle("0123456789"), 0, 3);
// Create the username for the account
$username = 'pk_' . $firstChar . $secondChar .'_' . $randomNum;
if ( empty( $username ) ) {
GFCommon::log_debug( __METHOD__ . '(): Value for username is empty.' );
return $username;
}
if ( ! function_exists( 'username_exists' ) ) {
require_once( ABSPATH . WPINC . '/registration.php' );
}
if ( username_exists( $username ) ) {
GFCommon::log_debug( __METHOD__ . '(): Username already exists, generating a new one.' );
$i = 2;
while ( username_exists( $username . $i ) ) {
$i++;
}
$username = $username . $i;
GFCommon::log_debug( __METHOD__ . '(): New username: ' . $username );
};
return $username;
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment