Created
July 16, 2020 12:39
-
-
Save andrewlimaza/15539fb4d5e834a630cef9f0b0a92ad2 to your computer and use it in GitHub Desktop.
Generate username from firstname and last name PMPro.
This file contains hidden or 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 | |
/** | |
* This requires billing fields to be enabled at checkout. | |
* Generate a username from firstname and lastname fields. If name exists will try to generate a random number after the username. | |
* Add this code to your site by following this guide - https://www.paidmembershipspro.com/create-a-plugin-for-pmpro-customizations/ | |
*/ | |
function my_generate_username_at_checkout() { | |
//check for level as well to make sure we're on checkout page | |
if(empty($_REQUEST['level'])) { | |
return; | |
} | |
if ( ! empty( $_REQUEST['bfirstname'] ) && ! empty( $_REQUEST['blastname'] ) ) { | |
$joined_name = $_REQUEST['bfirstname'] . $_REQUEST['blastname']; | |
$username = my_generate_username( $joined_name ); | |
} else { | |
$username = ''; | |
} | |
if ( ! empty( $_REQUEST['bemail'] ) ) { | |
$_REQUEST['username'] = $username; | |
} | |
if ( ! empty( $_POST['bemail'] ) ) { | |
$_POST['username'] = $username; | |
} | |
if( ! empty( $_GET['bemail'] ) ) { | |
$_GET['username'] = $username; | |
} | |
} | |
add_action('init', 'my_generate_username_at_checkout'); | |
/** | |
* Generate a username from a user's email address. | |
* Helper function. | |
*/ | |
function my_generate_username( $name ) { | |
while( username_exists( $name ) ) { | |
$name .= random_int( 0, 9999 ); | |
} | |
return sanitize_text_field( $name ); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment