Last active
April 26, 2019 16:39
-
-
Save gdarko/6a5c72dba684a2ea0bcf0f6340b94da6 to your computer and use it in GitHub Desktop.
GravityForms + User Registrations plugin: Use first name and last name in the form to generate username out of both. Append number if the username exists.
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 | |
/** | |
* Check if there is still pending registration for specific username | |
* @param $username | |
* | |
* @return bool | |
*/ | |
function dg_check_pending_registration($username) { | |
global $wpdb; | |
$table = $wpdb->prefix . 'signups'; | |
$query = $wpdb->prepare("SELECT COUNT(*) as count FROM {$table} WPS WHERE WPS.user_login='%s'", $username); | |
$total = $wpdb->get_var($query); | |
return $total > 0; | |
} | |
/** | |
* Generate username | |
* | |
* @param $form | |
* @param $feed | |
* @param $entry | |
* | |
* @return string | |
*/ | |
function dg_gf_generate_username($form, $feed, $entry) { | |
$username = ""; | |
// This is taking the field ids directly from User Registration feed (first name and last name) | |
$firstname = rgar($entry, $feed['meta']['first_name']); | |
$lastname = rgar($entry, $feed['meta']['last_name']); | |
if (!empty($firstname) || !empty($lastname)) { | |
$username = ''; | |
if (!empty($firstname)) { | |
$username.= $firstname; | |
} | |
if (!empty($lastname)) { | |
$username.= $lastname; | |
} | |
$username = strtolower($username); | |
} | |
// Generate random username, append numbers to joe if needed. | |
if (username_exists($username) || dg_check_pending_registration($username)) { | |
$i = 2; | |
while (username_exists($username . $i) || dg_check_pending_registration($username . $i)) { | |
$i++; | |
} | |
$username = $username . $i; | |
}; | |
return $username; | |
} | |
/** | |
* Generate WordPress username | |
* @param $username | |
* @param $feed | |
* @param $form | |
* @param $entry | |
* | |
* @return string | |
*/ | |
function dg_gform_username($username, $feed, $form, $entry) { | |
if (!function_exists('username_exists')) { | |
require_once (ABSPATH . WPINC . '/registration.php'); | |
} | |
$_username = dg_gf_generate_username($form, $feed, $entry); | |
if (!empty($_username)) { | |
$username = $_username; | |
} | |
return $username; | |
} | |
add_filter('gform_username', 'dg_gform_username', 0, 4); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment