Using WordPress ‘get_user_meta()’ PHP function

The get_user_meta() WordPress PHP function retrieves user meta field(s) for a user.

Usage

get_user_meta( $user_id, $key, $single )

Custom example:
get_user_meta( 1, 'user_bio', true );

Parameters

  • $user_id int (Required) – The User ID.
  • $key string (Optional) – The meta key to retrieve. By default, returns data for all keys. Default: ”.
  • $single bool (Optional) – Whether to return a single value. This parameter has no effect if $key is not specified. Default: false.

More information

See WordPress Developer Resources: get_user_meta()

Examples

Retrieve user’s last name

Retrieve and display the last name for user id 9:

$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>';

Retrieve all user meta data

Retrieve all meta data for a specific user (user_id = 9) and filter out empty values:

$user_id = 9;
$meta = get_user_meta( $user_id );

// Filter out empty meta data
$meta = array_filter( array_map( function( $a ) { return $a[0]; }, $meta ) );

Check if returned value is empty

Check if a user’s permission meta field is empty:

global $current_user;
get_currentuserinfo();
if ( $current_user ) {
    $permission = get_user_meta( $current_user->ID, 'permission', true );
    if ( empty( $permission ) ) {
        echo "User permission meta field is empty.";
    } else {
        echo "User permission: " . $permission;
    }
}

Update user meta data

Update a user’s bio, and then retrieve and display the updated value:

$user_id = 1;
update_user_meta( $user_id, 'user_bio', 'I am a WordPress developer.' );
$user_bio = get_user_meta( $user_id, 'user_bio', true );
echo 'User bio: ' . $user_bio;

Retrieve user meta data for multiple users

Retrieve the ‘last_name’ meta data for multiple users (with user IDs 1, 2, and 3) and display the results:

$user_ids = array( 1, 2, 3 );
$key = 'last_name';

foreach ( $user_ids as $user_id ) {
    $user_last = get_user_meta( $user_id, $key, true );
    echo '<p>The '. $key . ' value for user id ' . $user_id . ' is: ' . $user_last . '</p>';
}