Function and usage of get_userdata() in wordpress


Answers ( 1 )


    The get_userdata() function in WordPress is used to retrieve user information based on a user ID. Here's a detailed explanation:

    Function: get_userdata( int $user_id )


    To retrieve user information by their user ID.


    • $user_id (int, required): The user ID for which information is to be retrieved.

    Return Value:

    • WP_User | false: Returns a WP_User object on success, which contains all the user's data. If the user ID does not exist or the user cannot be found, it returns false.

    Sample Usage:

    $user_id = 1; // Example user ID
    $user_info = get_userdata( $user_id );
    if ( $user_info ) {
        echo 'Username: ' . $user_info->user_login . "\n";
        echo 'User email: ' . $user_info->user_email . "\n";
        echo 'User first name: ' . $user_info->first_name . "\n";
        echo 'User last name: ' . $user_info->last_name . "\n";
        // ... other properties
    } else {
        echo 'User not found.';

    In this example:

    1. We specify a user ID (in this case, 1).
    2. We use get_userdata() to retrieve the user's information.
    3. If the user exists, their information is printed (username, email, first name, last name, etc.).
    4. If the user does not exist (i.e., get_userdata() returns false), a message 'User not found' is displayed.

    This function is especially useful for developers who need to access or display user information on a WordPress site, whether for customizing user profiles, creating member directories, or similar tasks.

Leave an answer