Set username by using sanitized first and last name.
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 | |
/** | |
* 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