Skip to content

Instantly share code, notes, and snippets.

@2ndkauboy
Created October 10, 2021 21:33
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 2ndkauboy/42eda2a062a0d2de5d64c4dd8755753a to your computer and use it in GitHub Desktop.
Save 2ndkauboy/42eda2a062a0d2de5d64c4dd8755753a to your computer and use it in GitHub Desktop.
Set username by using sanitized first and last name.
<?php
/**
* Plugin Name: GravityForms Multisite Username Fix
* @package GravityFormsMultisiteUsernameFix
* @author Bernhard Kau
* @license GPLv3
*
* @wordpress-plugin
* Plugin Name: GravityForms Multisite Username Fix
* Plugin URI: https://kau-boys.de
* Description: Use first and last name for a sanitized and unique username.
* Version: 0.1
* Author: Bernhard Kau
* Author URI: https://kau-boys.de
* License: GPLv3
* License URI: http://www.gnu.org/licenses/gpl-3.0.txt
*/
/**
* Set username by using sanitized first and last name.
*
* @param string $username The username of the being created
* @param array $feed The Feed object
* @param array $form The Form object
* @param array $entry The Entry object
*/
function gf_ms_uf_set_username( $username, $feed, $form, $entry ) {
// Get first and last name from the form submission.
$first_name = rgar( $entry, rgars( $feed, 'meta/first_name' ) );
$last_name = rgar( $entry, rgars( $feed, 'meta/last_name' ) );
// Generate a new username making it compatible with multisite constraints.
$new_username = gf_ms_uf_get_unique_username( sanitize_user( $first_name . $last_name ) );
if ( ! empty ( $new_username ) ) {
$username = $new_username;
}
return $username;
}
add_filter( 'gform_username', 'gf_ms_uf_set_username', 10, 4 );
function gf_ms_uf_get_unique_username( $username ) {
$number = 2;
$original_username = $username;
while ( username_exists( $username ) || gf_ms_uf_is_user_signed_up( $username ) ) {
$username = $original_username . $number ++;
}
return $username;
}
function gf_ms_uf_is_user_signed_up( $username ) {
global $wpdb;
return $wpdb->get_row( $wpdb->prepare( "SELECT * FROM $wpdb->signups WHERE user_login = %s", $username ) );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment