add_user_meta()
Adds metadata to the specified user.
To add user metadata, you can also use the function update_user_meta(). It will add the field if it does not exist. The difference with this function is that you do not need to specify $unique (leave it false), which allows you to add multiple fields with the same key.
User metadata is analogous to custom fields in posts. They are stored in the wp_usermeta table. To better understand what this metadata is, for example, such familiar user data as: first_name (first name), last_name (last name), nickname (Nick), are recorded in these user meta fields.
No Hooks.
Returns
Int|false. The identifier of the added key (the field of the table with the primary key) or false if the field could not be added.
Usage
add_user_meta( $user_id, $meta_key, $meta_value, $unique );
- $user_id(integer) (required)
- User ID.
- $meta_key(string) (required)
- User meta field key.
- $meta_value(string/array/integer/object/boolean)
- User meta field value.
- $unique(boolean)
- If true, the field will be added only if a field with the same key does not already exist. false - will add another field with the same key if such a field already exists.
Default: false
Examples
#1 Multiple fields with the same key
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
#2 Demo
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() add user meta code WP 7.0
function add_user_meta( $user_id, $meta_key, $meta_value, $unique = false ) {
return add_metadata( 'user', $user_id, $meta_key, $meta_value, $unique );
}