add_user_meta()WP 3.0.0

Adds meta data to a user.

No Hooks.

Returns

Int|false. Meta ID on success, false on failure.

Usage

add_user_meta( $user_id, $meta_key, $meta_value, $unique );
$user_id(int) (required)
User ID.
$meta_key(string) (required)
Metadata name.
$meta_value(mixed) (required)
Metadata value. Arrays and objects are stored as serialized data and will be returned as the same type when retrieved. Other data types will be stored as strings in the database:
  • false is stored and retrieved as an empty string ('')
  • true is stored and retrieved as '1'
  • numbers (both integer and float) are stored and retrieved as strings Must be serializable if non-scalar.
$unique(true|false)
Whether the same key should not be added.
Default: false

Examples

2

#1 Multiple fields with the same key [auto-translate]

This example shows how to add multiple fields with the same keys, we will not specify the parameter $unique but leave it false. For example, let's say the user specifies books he has read in a special field, there can be several such books and we will write their names in fields with the same key book:

$user_id = 1;

// add one book
$read_book = 'Metro 2033;
add_user_meta( $user_id, 'book', $read_book );

// add a second book
$read_book2 = 'A Seagull Called Jonathan Livingston;
add_user_meta( $user_id, 'book', $read_book2 );

// now we have 2 posts in the table wp_usermeta with the same book key
0

#2 Demo [auto-translate]

Add the meta field _level_of_awesomeness for the user with ID 1:

$user_id = 1;
$awesome_level = 1000;
add_user_meta( $user_id, '_level_of_awesomeness', $awesome_level, true );

Changelog

Since 3.0.0 Introduced.

add_user_meta() code WP 6.8.1

function add_user_meta( $user_id, $meta_key, $meta_value, $unique = false ) {
	return add_metadata( 'user', $user_id, $meta_key, $meta_value, $unique );
}