The add_user_meta() WordPress PHP function adds metadata to a specific user in your WordPress database.
Usage
This function is used to attach additional information, or “meta”, to a user. Here’s a basic usage example:
$user_id = 10; // Let's assume this is the ID of the user $meta_key = 'favourite_color'; $meta_value = 'blue'; $unique = true; // This ensures the meta key is unique for the user add_user_meta($user_id, $meta_key, $meta_value, $unique);
Parameters
- $user_id (int): The ID of the user to whom the metadata will be added.
- $meta_key (string): The name of the metadata.
- $meta_value (mixed): The value of the metadata. It can be any type, but must be serializable if non-scalar.
- $unique (bool): Optional. If set to true, the same key will not be added if it already exists for the user. Default is false.
More information
See WordPress Developer Resources: add_user_meta
This function has been implemented since WordPress version 3.0.0.
Examples
Adding User Bio
In this example, we’re adding a short bio to the user.
$user_id = 10; $meta_key = 'bio'; $meta_value = 'I love coding and pizza.'; add_user_meta($user_id, $meta_key, $meta_value, true);
Recording User’s Favorite Book
Here we’re recording the user’s favorite book.
$user_id = 15; $meta_key = 'favorite_book'; $meta_value = 'The Great Gatsby'; add_user_meta($user_id, $meta_key, $meta_value, true);
Saving User’s Subscription Status
Let’s save whether the user has an active subscription or not.
$user_id = 20; $meta_key = 'subscription_status'; $meta_value = 'active'; add_user_meta($user_id, $meta_key, $meta_value, true);
Storing User’s Preferred Language
This example shows how to store the user’s preferred language.
$user_id = 25; $meta_key = 'preferred_language'; $meta_value = 'Spanish'; add_user_meta($user_id, $meta_key, $meta_value, true);
Adding a User’s Score
We can also use this function to add a score to a user, for instance in a game or quiz.
$user_id = 30; $meta_key = 'score'; $meta_value = 1500; add_user_meta($user_id, $meta_key, $meta_value, true);