Forked from JarrydLong/generate-username-from-email-pmpro.php
Last active
December 30, 2024 15:37
-
-
Save kimwhite/b51178c89f1f428c6e14d0e90cb587c5 to your computer and use it in GitHub Desktop.
Generate a username during checkout for user [Paid Memberships Pro]
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 | |
/** | |
* 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() { | |
// add this for manage groups to work | |
if ( ! empty( $_REQUEST['pmprogroupacct_create_member_email'] ) ) { | |
$_REQUEST['pmprogroupacct_create_member_username'] = my_pmpro_generate_username_from_email( $_REQUEST['pmprogroupacct_create_member_email'] ); | |
} | |
// end manage groups to work | |
// 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] ); | |
} | |
/** | |
* Loads styling in the footer to hide the username field | |
*/ | |
add_action( 'wp_footer', function () { | |
?> | |
<style> | |
/* Hide the username field on checkout. */ | |
.pmpro_form_field-username { | |
display: none !important; | |
} | |
</style> | |
<?php | |
} ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment