Last active
March 11, 2022 20:56
-
-
Save sc0ttkclark/b4f0d721b51ba1baf1b0e016479a373a to your computer and use it in GitHub Desktop.
Automatically update the display name to be set as the first/last name when the user is registered or the profile is saved or during checkout.
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 | |
/** | |
* Automatically update the display name to be set as the first/last name when the user is registered or the profile is saved. | |
* | |
* You can add this recipe to your site by creating a custom plugin | |
* or using the Code Snippets plugin available for free in the WordPress repository. | |
* Read this companion article for step-by-step directions on either method. | |
* https://www.paidmembershipspro.com/create-a-plugin-for-pmpro-customizations/ | |
*/ | |
add_action( 'user_register', 'my_pmpro_set_user_display_name_as_first_last_on_profile_save' ); | |
add_action( 'profile_update', 'my_pmpro_set_user_display_name_as_first_last_on_profile_save' ); | |
function my_pmpro_set_user_display_name_as_first_last_on_profile_save( $user_id ) { | |
// Get the user object. | |
$data = get_userdata( $user_id ); | |
// Set up the new display name based on the first/last name. | |
$new_display_name = trim( $data->first_name . ' ' . $data->last_name ); | |
// Check whether the display name matches the login AND that the display name is not already the same as the first/last name. | |
if ( | |
$data->display_name === $data->user_login | |
&& '' !== $new_display_name | |
&& $data->display_name !== $new_display_name | |
) { | |
// Update the display name to the first/last name. | |
wp_update_user( [ | |
'ID' => $user_id, | |
'display_name' => $new_display_name, | |
] ); | |
} | |
} | |
add_filter( 'pmpro_checkout_new_user_array', 'my_pmpro_set_user_display_name_as_first_last_on_checkout' ); | |
function my_pmpro_set_user_display_name_as_first_last_on_checkout( $user_data ) { | |
// Set up the new display name based on the first/last name. | |
$new_display_name = trim( $user_data['first_name'] . ' ' . $user_data['last_name'] ); | |
if ( '' !== $new_display_name ) { | |
$user_data['display_name'] = $new_display_name; | |
} | |
return $user_data; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment