Last active
December 2, 2024 13:54
-
-
Save andrewlimaza/daf8890246df14cfe3d880634ddb5098 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 email 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() { | |
// Make sure PMPro is installed and the function to get the level at checkout exists. | |
if ( ! function_exists( 'pmpro_getLevelAtCheckout' ) ) { | |
return; | |
} | |
// check for level as well to make sure we're on checkout page | |
if ( empty( pmpro_getLevelAtCheckout() ) ) { | |
return; | |
} | |
if ( ! empty( $_POST['bemail'] ) ) { | |
$_REQUEST['username'] = $_POST['username'] = my_pmpro_generate_username_from_email( $_POST['bemail'] ); | |
} | |
if ( ! empty( $_GET['bemail'] ) ) { | |
$_REQUEST['username'] = $_GET['username'] = my_pmpro_generate_username_from_email( $_GET['bemail'] ); | |
} | |
} | |
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 email address. | |
* Helper function. | |
*/ | |
function my_pmpro_generate_username_from_email( $email ) { | |
$parts = explode( '@', $email ); | |
while ( username_exists( $parts[0] ) ) { | |
$parts[0] .= random_int( 0, 9999 ); | |
} | |
return sanitize_text_field( $parts[0] ); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This recipe is included in the blog post on "Customizing Usernames on Your Membership Site" at Paid Memberships Pro here: https://www.paidmembershipspro.com/customizing-usernames-for-your-membership-site/