Whenever I update a user profile in the dashboard, the user nice-name gets changed in the database: Every time, a “-2” is added.
I tried to reset the nicename (based loosely on this thread) by hooking into edit_user_profile_update
and personal_options_update
, but that seems to be to early, the value does not change:
add_action( 'personal_options_update', 'my_reset_nicename_function' );
add_action( 'edit_user_profile_update', 'my_reset_nicename_function' );
function my_reset_nicename_function( $user_id ) {
$user = new WP_User( $user_id );
$nice_name = $_POST['first_name'] . ' ' . $_POST['last_name'];
$nice_name = sanitize_text_field( $display_name );
wp_update_user( array(
'ID' => $user->ID,
'user_nicename' => $display_name
) );
}
Then I read about the pre_user_nicename
-filter (which feels like a much cleaner way), but any callback function filtering the nicename only gets the nicename as an argument, and one cannot get a user-object by its nicename only:
add_filter( 'pre_user_nicename','my_user_nicename_filter_function' ) );
function my_user_nicename_filter_function( $user_nicename ) {
// How to get the user's firstname or lastname here?
}
So, how can I reset the user’s nice-name to his first- and lastname when saving his profile in the dashboard?
EDIT: When I deactivate my pre_user_login
callback (to automatically define the user_logins), the above behaviour does not occur. Can anybody please give me a push?