函数文档

get_userdata()

💡 云策文档标注

概述

get_userdata() 函数通过用户 ID 检索用户信息,返回一个 WP_User 对象或失败时返回 false。它是基于 get_user_by() 的封装函数,常用于获取用户数据以进行显示或权限检查。

关键要点

  • 参数:$user_id(整数,必需),指定要检索的用户 ID。
  • 返回值:成功时返回 WP_User 对象,失败时返回 false。
  • 内部实现:调用 get_user_by('id', $user_id) 来获取用户数据。
  • 用途广泛:被多个核心函数和类使用,涉及用户管理、权限验证、REST API、XML-RPC 等场景。

代码示例

$user_info = get_userdata(1);
echo 'Username: ' . $user_info->user_login . "n";
echo 'User roles: ' . implode(', ', $user_info->roles) . "n";
echo 'User ID: ' . $user_info->ID . "n";

注意事项

  • 确保传入有效的用户 ID,否则可能返回 false。
  • 返回的 WP_User 对象包含用户的基本信息和元数据,可通过对象属性访问(如 user_login、roles、first_name 等)。
  • 在性能敏感场景中,考虑直接使用 get_user_by() 或其他缓存机制。

📄 原文内容

Retrieves user info by user ID.

Parameters

$user_idintrequired
User ID

Return

WP_User|false WP_User object on success, false on failure.

Source

function get_userdata( $user_id ) {
	return get_user_by( 'id', $user_id );
}

Changelog

Version Description
0.71 Introduced.

User Contributed Notes

  1. Skip to note 4 content

    Basic Usage
    The get_userdata() function returns an object of the user’s data. You can echo various parts of the returned object or loop through the data to display it all.

    Example displaying certain parts:

    user_login . "n";
          echo 'User roles: ' . implode(', ', $user_info->roles) . "n";
          echo 'User ID: ' . $user_info->ID . "n";
    ?>

    Results in:

    Username: admin
    User roles: administrator
    User ID: 1

    You can also assign certain parts into individual variables for displaying later or in multiple places.

    Example for extracting certain parts:

    user_login;
          $first_name = $user_info->first_name;
          $last_name = $user_info->last_name;
          echo "$first_name $last_name logs into her WordPress site with the user name of $username.";
    ?>

    Results in:

    Harriet Smith logs into her WordPress site with the user name of mrssmith.