Get the user ID by login in WordPress with a simple function

Recently I needed to get the ID of a user out of a big list. I didn’t want to open the database or search for the number in the WP Admin. I wanted to get it with a PHP function. So here is how I did it in the WordPress way without writing plain SQL statements:

function get_user_id_by_login( string $string ) {
    $user = get_user_by( 'login', $string );
    
    if ( $user ) {
        return $user->ID;
    }

    return null;
}

The above function will return an integer if the user with that username exists or null otherwise.

Example: How to set the password of a user

This is a simple code that I often set on top of the functions.php when I want to quickly replace the password of a user in dev, or test environments.

wp_set_password('12345678', get_user_id_by_login('john_doe'));

Member since January 2, 2019

As a seasoned WordPress developer with expertise in various tech stacks and languages, I bring years of experience to every project I handle. My passion for coding and dedication to delivering exceptional work ensures that each project I take on is of the highest quality. I specialize in creating custom themes, developing plugins, and building full-scale web systems. By staying up-to-date with the latest industry trends and best practices, I incorporate cutting-edge solutions into my work.

Comments

    Your email address will not be published. Required fields are marked *