Forked from andrewlimaza/generate-username-from-email-pmpro.php
Last active
October 19, 2023 17:37
-
-
Save MaximilianoRicoTabo/a19b215cd53cf5033d18905d5f40e143 to your computer and use it in GitHub Desktop.
Generate a username during checkout for user [Paid Memberships Pro]
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 | |
/** | |
* Generate a username at PMPro checkout from first and last name for users. | |
* Hide your 'username' field using custom CSS. | |
* Add this code to your site by following this guide - https://www.paidmembershipspro.com/create-a-plugin-for-pmpro-customizations/ | |
*/ | |
function my_pmpro_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['first_name']) && !empty($_REQUEST['last_name']) ) { | |
$_REQUEST['username'] = my_pmpro_generate_username_from_email( $_REQUEST['first_name'], $_REQUEST['last_name'] ); | |
} | |
if (!empty($_POST['first_name']) && !empty($_POST['last_name']) ) { | |
$_POST['username'] = my_pmpro_generate_username_from_email($_POST['first_name'], $_POST['last_name']); | |
} | |
if (!empty($_GET['first_name']) && !empty($_GET['last_name']) ) { | |
$_GET['username'] = my_pmpro_generate_username_from_email($_GET['first_name'], $_GET['last_name']); | |
} | |
} | |
add_action('init', 'my_pmpro_generate_username_at_checkout'); | |
/** | |
* Hide the username field on checkout. | |
*/ | |
function my_pmpro_unset_required_username_checkout( $pmpro_required_user_fields ) { | |
unset( $pmpro_required_user_fields['username'] ); | |
return $pmpro_required_user_fields; | |
} | |
add_filter('pmpro_required_user_fields', 'my_pmpro_unset_required_username_checkout', 10, 2); | |
/** | |
* Generate a username from a user's first and last name. | |
* Helper function. | |
*/ | |
function my_pmpro_generate_username_from_email($first_name, $last_name) { | |
$proposed_name = sanitize_text_field( strtolower( $first_name ) . '.' . strtolower( $last_name ) ); | |
$user_name_already_exists = get_user_by( 'login', $proposed_name ); | |
if(! $user_name_already_exists ) { | |
return $proposed_name; | |
} else { | |
return $proposed_name . pmpro_getDiscountCode(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment