pmpro_generateUsername

The Paid Memberships Pro pmpro generateUsername function.

Description

pmpro_generateUsername( (string) $firstname = '', (string) $lastname = '', (string) $email = '' ); 

Parameters (3)

0. $firstname — Optional. (string) => ''
The firstname.
1. $lastname — Optional. (string) => ''
The lastname.
2. $email — Optional. (string) => ''
The email.

Usage

  1. if ( !function_exists( 'pmpro_generateUsername' ) ) { 
  2. require_once ABSPATH . PLUGINDIR . 'paid-memberships-pro/includes/functions.php'; 
  3.  
  4. // The firstname. 
  5. $firstname = ''; 
  6.  
  7. // The lastname. 
  8. $lastname = ''; 
  9.  
  10. // The email. 
  11. $email = ''; 
  12.  
  13. // NOTICE! Understand what this does before running. 
  14. $result = pmpro_generateUsername($firstname, $lastname, $email); 
  15.  

Defined (1)

The function is defined in the following location(s).

/includes/functions.php  
  1. function pmpro_generateUsername($firstname = "", $lastname = "", $email = "") 
  2. global $wpdb; 
  3.  
  4. //try first initial + last name, firstname, lastname 
  5. $firstname = preg_replace("/[^A-Za-z]/", "", $firstname); 
  6. $lastname = preg_replace("/[^A-Za-z]/", "", $lastname); 
  7. if($firstname && $lastname) 
  8. $username = substr($firstname, 0, 1) . $lastname; 
  9. elseif($firstname) 
  10. $username = $firstname; 
  11. elseif($lastname) 
  12. $username = $lastname; 
  13.  
  14. //is it taken? 
  15. $taken = $wpdb->get_var("SELECT user_login FROM $wpdb->users WHERE user_login = '" . esc_sql($username) . "' LIMIT 1"); 
  16.  
  17. if(!$taken) 
  18. return $username; 
  19.  
  20. //try the beginning of the email address 
  21. $emailparts = explode("@", $email); 
  22. if(is_array($emailparts)) 
  23. $email = preg_replace("/[^A-Za-z]/", "", $emailparts[0]); 
  24.  
  25. if(!empty($email)) 
  26. $username = $email; 
  27.  
  28. //is this taken? if not, add numbers until it works 
  29. $taken = true; 
  30. $count = 0; 
  31. while($taken) 
  32. //add a # to the end 
  33. if($count) 
  34. $username = preg_replace("/[0-9]/", "", $username) . $count; 
  35.  
  36. //taken? 
  37. $taken = $wpdb->get_var("SELECT user_login FROM $wpdb->users WHERE user_login = '" . esc_sql($username) . "' LIMIT 1"); 
  38.  
  39. //increment the number 
  40. $count++; 
  41.  
  42. //must have a good username now 
  43. return $username;