gform_username

Description

This filter is used to dynamically alter or generate a username during the registration process.

Usage

The base filter which would run for all forms would be used like so:

add_filter( 'gform_username', 'your_function_name', 10, 4 );

To target a specific form append the form id to the hook name. (format: gform_username_FORMID)

add_filter( 'gform_username_4', 'your_function_name', 10, 4 );

Parameters

  • $username string

    The value of the username as submitted by the user.

  • $feed Feed Object

    The Feed which is currently being processed.

  • $form Form Object

    The current form object.

  • $entry Entry Object

    The current entry object.

Examples

This example retrieves the first and last name values of a Name field, combines them without spaces or special characters, and assigns that value as the username. It checks if that username exists and if so, appends an integer to the username (i.e., 2, 3, 4) until it finds a username plus integer combination that does not yet exist.

To use this example you need to update the inputs id numbers with the correct values for your name field, and update the filter name to use your form id number. Check the comment in the snippet.

// Change 8 in gform_username_8 to your form id number.
add_filter( 'gform_username_8', '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
$username = strtolower( rgar( $entry, '2.3' ) . rgar( $entry, '2.6' ) );

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;
}

Placement

This code should be placed in the functions.php file of your active theme.

Source Code

$username = gf_apply_filters( 'gform_username', $form['id'], $username, $feed, $form, $entry );

This filter is located in GF_User_Registration::validate() and GF_User_Registration::get_user_data() in class-gf-user-registration.php.