Last active
April 5, 2024 20:00
-
-
Save christianwach/5f07b5cbc0b9067d2353e13cd19806be to your computer and use it in GitHub Desktop.
Enforces the format of the BuddyPress Name field and WordPress Display Name field.
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 | |
/** | |
* Plugin Name: BP Enforce Display Name | |
* Description: Enforces the format of the BuddyPress Name field and WordPress Display Name field. | |
* Plugin URI: https://gist.github.com/christianwach/5f07b5cbc0b9067d2353e13cd19806be | |
* Version: 1.0 | |
* Author: Christian Wach | |
* Author URI: https://github.com/christianwach | |
*/ | |
add_action( 'user_register', 'bpedn_update_display_name', 100, 1 ); | |
add_action( 'profile_update', 'bpedn_update_display_name', 100, 1 ); | |
/** | |
* Update the WordPress User "Display Name" field. | |
* | |
* @since 1.0 | |
* | |
* @param integer $user_id The numeric ID of the WordPress User. | |
*/ | |
function bpedn_update_display_name( $user_id ) { | |
// Bail if BuddyPress is not active. | |
if ( ! function_exists( 'xprofile_set_field_data' ) ) { | |
return; | |
} | |
// Get the User record. | |
$user = new WP_User( $user_id ); | |
if ( ! $user->exists() ) { | |
return; | |
} | |
/* | |
* Construct the "Display Name" the way BuddyPress used to. | |
* | |
* There are, of course, many options for this - so you may want to adapt | |
* this line of code to suit your own requirements. | |
*/ | |
$full_name = $user->first_name . ' ' . $user->last_name; | |
// Remove our callbacks. | |
remove_action( 'user_register', 'bpedn_update_display_name', 100 ); | |
remove_action( 'profile_update', 'bpedn_update_display_name', 100 ); | |
// Build update args. | |
$args = [ | |
'ID' => $user_id, | |
'display_name' => $full_name, | |
]; | |
// Update the WordPress User record. | |
wp_update_user( $args ); | |
// Update BuddyPress "Name" field directly. | |
xprofile_set_field_data( | |
bp_xprofile_fullname_field_name(), | |
$user_id, | |
$full_name | |
); | |
// Reinstate our callbacks. | |
add_action( 'user_register', 'bpedn_update_display_name', 100, 1 ); | |
add_action( 'profile_update', 'bpedn_update_display_name', 100, 1 ); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment