get_user_meta()获取一个用户的meta自定义附加信息

目录

描述

Retrieve a single meta field or all fields of user_meta data for the given user. Uses get_metadata(). This function replaces the deprecated get_usermeta() function.

get_user_meta() 描述

用法

<?php get_user_meta($user_id$key$single);  ?>

get_user_meta() 用法

参数

$user_id

(integer) (必填) The ID of the user whose data should be retrieved.

默认值: None

$key

(string) (可选) The meta_key in the wp_usermeta table for the meta_value to be returned. If left empty, will return all user_meta fields for the given user.

默认值: (empty string)

$single

(boolean) (可选) If true return value of meta data field, if false return an array. This parameter has no effect if $key is left blank.

默认值: false

get_user_meta() 参数

返回值

(mixed) 

Will be an Array if $key is not specified or if $single is false. Will be value of meta_value field if $single is true.

NOTE

If the meta value does not exist and $single is true the function will return an empty string. If $single is false an empty array is returned.

get_user_meta() 返回值

示例

This example returns and then displays the last name for user id 9.

The last_name value for user id 9 is Franklin

Getting all meta data

This example demonstrates leaving the $key argument blank, in order to retrieve all meta data for the given user (in this example, user_id = 9):

Results:

Note: in order to access the data in this example, you need to dereference the array that is returned for each key, like so:

To avoid this, you may want to run a simple array_map() on the results of get_user_meta() in order to take only the first index of each result (this emulating what the $single argument does when $key is provided:

Results:

Additionally, if you want to return ALL meta for a specific user and filter out empty values, you can run array_filter() on the results of the array_map() above:

get_user_meta() 示例

注意

Please note that if the meta value exists but is empty, it will return an empty string (or array) as if the meta value didn't exist. This might cause unexpected behaviours in your code when you empty the user meta, your code can try to use add_user_meta instead of update_user_meta thinking the user does not have meta created yet. I think get_user_meta should return false if it doesn't exist.

Filters

get_user_meta() 注意

历史

添加于 版本: 3.0

get_user_meta() 历史

源文件

get_user_meta() 函数的代码位于 wp-includes/user.php.

get_user_meta() 源文件

相关