apply_filters( ‘pre_user_login’, string $sanitized_user_login )

Filters a username after it has been sanitized.

Description

This filter is called before the user is created or updated.

Parameters

$sanitized_user_loginstring
Username after it has been sanitized.

Source

$pre_user_login = apply_filters( 'pre_user_login', $sanitized_user_login );

Changelog

VersionDescription
2.0.3Introduced.

User Contributed Notes

  1. Skip to note 2 content

    This filter is run before a user is created and/or updated. The fact that all pre_user hooks are run in both conditions makes life a bit more complicated.

    The filter is referenced in both wp-admin/user-new.php and wp-includes/user.php

    Here’s an example of using it to make sure a newly created user has a nickname equal to the user’s first and last name:

    /**
     * Check if the user has been created.
     *
     * @param string $login User login.
     * @return string (Maybe) filtered login.
     */
    function wpdocs_check_if_user_created( $login ) {
    	// Don't do anything to login, just see if already in database.
    	global $wpdb, $is_new_login;
    
    	$id = $wpdb->get_var( $wpdb->prepare( "SELECT ID FROM $wpdb->users WHERE user_login = '%s'", $login ) );
    	$is_new_login = ( isset( $id ) ) ? false : true;
    
    	return $login;
    }
    
    /**
     * Filter the user nickname.
     *
     * @param string $nickname User nickname.
     * @return string (Maybe) filtered nickname.
     */
    function wpdocs_fix_nickname ( $nickname ) {
    	global $is_new_login;
    
    	if ( $is_new_login ) {
    		$first_name = empty( $_POST_['first_name'] ) ? sanitize_text_field( $_POST['first_name'] ) : '';
    		$last_name  = empty( $_POST['last_name'] ) ? sanitize_text_field( $_POST['last_name'] ) : '';
    
    		$nickname  = empty( $first_name ) ? '' : $first_name;
    		$nickname .= empty( $last_name ) ? '' : ' ' . $last_name;
    	}
    	return $nickname;
    }
    
    add_filter( 'pre_user_login', 'wpdocs_check_if_user_created' );
    add_filter( 'pre_user_nickname', 'wpdocs_fix_nickname' );

You must log in before being able to contribute a note or feedback.