Using Gravity Forms ‘gform_username’ PHP filter

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

Usage

A generic example of using the filter for all forms:

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

To target a specific form, append the form ID to the hook name:

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 currently being processed.
  • $form (Form Object) – The current form object.
  • $entry (Entry Object) – The current entry object.

More information

See Gravity Forms Docs: gform_username

Examples

Generate username from first and last name

This example retrieves the first and last name values from a Name field, combines them without spaces or special characters, and assigns that value as the username. If the username already exists, it appends an integer to the username (e.g., 2, 3, 4) until it finds a unique username.

Replace the form ID and Name field input IDs with the correct values for your form.

// Replace 8 in gform_username_8 with 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., 1.3 and 1.6 if your Name field has ID 1)
    $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;
}