get_user_meta( int $user_id, string $key = '', bool $single = false )
Retrieve user meta field for a user.
Description Description
Parameters Parameters
- $user_id
-
(int) (Required) User ID.
- $key
-
(string) (Optional) The meta key to retrieve. By default, returns data for all keys.
Default value: ''
- $single
-
(bool) (Optional) Whether to return a single value.
Default value: false
Return Return
(mixed) Will be an array if $single is false. Will be value of meta data field if $single is true.
Source Source
File: wp-includes/user.php
function get_user_meta( $user_id, $key = '', $single = false ) {
return get_metadata( 'user', $user_id, $key, $single );
}
Expand full source code Collapse full source code View on Trac
Changelog Changelog
| Version | Description |
|---|---|
| 3.0.0 | Introduced. |
User Contributed Notes User Contributed Notes
You must log in before being able to contribute a note or feedback.
If the key does not exist the function will return an empty string or an empty array depending on the value of the $single parameter
Feedback
It will also return boolean
falseif! is_numeric( $user_id )or! absint( $user_id ). — By thenbrent —Getting all meta data
This example demonstrates leaving the
$keyargument blank, in order to retrieve all meta data for the given user (in this example,user_id = 9):Results:
Array ( [first_name] => Array ( [0] => Tom ) [last_name] => Array ( [0] => Auger)[nickname] => Array ( [0] => tomauger ) [description] => etc.... )
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 ofget_user_meta()in order to take only the first index of each result (thus emulating what the$singleargument does when$keyis provided:$all_meta_for_user = array_map( function( $a ){ return $a[0]; }, get_user_meta( $user_id ) ); print_r( $all_meta_for_user );Results:
Array ( [first_name] => Tom [last_name] => Auger [nickname] => tomauger [description] => etc.... )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 thearray_map()above:// Get all user meta data for $user_id $meta = get_user_meta( $user_id ); // Filter out empty meta data $meta = array_filter( array_map( function( $a ) { return $a[0]; }, $meta ) );To check if returned value is empty, ie does not exist, you could use something like:
global $current_user; get_currentuserinfo(); if ( $current_user ) { $permission = get_user_meta( $current_user->ID, 'some_meta' , true ); if ( ! empty( $permission ) ) { // do stuff } } // works for both array and single valuesFeedback
The function get_currentuserinfo() is deprecated: http://wpsocket.com/wpref/function/get_currentuserinfo/ — By Jacob Hill —
This example returns and then displays the last name for user id 9.
Result:
The last_name value for user id 9 is Franklin