Function and usage of add_user_meta() in wordpress


Answers ( 1 )


    The add_user_meta() function in WordPress is used to add custom meta data to a user's profile. This function is particularly useful when you need to store additional information about users that isn't covered by the default WordPress user profile fields.

    Function Definition

    add_user_meta( int $user_id, string $meta_key, mixed $meta_value, bool $unique = false ): int|false


    1. $user_id (int, required): This is the ID of the user to whom you want to add the meta data. It's important that the user ID is valid and exists in the database.

    2. $meta_key (string, required): The key or name of the meta data you want to add. This should be a unique identifier for the piece of data you are storing.

    3. $meta_value (mixed, required): The value of the meta data. This can be any data type, but if it's an array or object, it must be serializable. WordPress will serialize this data before storing it in the database.

    4. $unique (bool, optional): This is a boolean value that determines whether the same key (meta_key) should be added if it already exists for the user. If set to true, WordPress will not add the meta data if the key already exists. The default value is false.

    Return Value

    The function returns the meta ID (integer) on successful addition of the meta data. If the function fails to add the meta data, it returns false.

    Sample Usage

    $user_id = 1; // Assuming a user ID of 1
    $meta_key = 'favorite_color';
    $meta_value = 'Blue';
    $result = add_user_meta($user_id, $meta_key, $meta_value, true);
    if ($result === false) {
        echo 'Failed to add meta data';
    } else {
        echo 'Meta data added successfully. Meta ID: ' . $result;

    In this example, we're adding a meta data with the key 'favorite_color' and the value 'Blue' to the user with the ID of 1. We've set the $unique parameter to true, meaning if the 'favorite_color' meta key already exists for this user, the function will not add it again and will return false. If the meta data is added successfully, it returns the meta ID.

Leave an answer