Contents[hide]
|
Retrieve a single meta field or all fields of user_meta data for the given user. Uses get_metadata(). This function replaces the deprecatedget_usermeta() function.
<?php get_user_meta($user_id, $key, $single); ?>
This example returns and then displays the last name for user id 9.
<?php $user_id = 9; $key = 'last_name'; $single = true; $user_last = get_user_meta( $user_id, $key, $single ); echo '<p>The '. $key . ' value for user id ' . $user_id . ' is: ' . $user_last . '</p>'; ?>
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):
<?php $all_meta_for_user = get_user_meta( 9 ); print_r( $all_meta_for_user ); ?>
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:
$last_name = $all_meta_for_user['last_name'][0];
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:
$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 runarray_filter() on the results of the array_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 ) );
Since: 3.0
get_user_meta() is located in wp-includes/user.php
.
add_user_meta(), delete_user_meta(), get_user_meta(), update_user_meta(), get_user_option(),delete_user_option(), update_user_option(),