Deep dive into WordPress user meta functions
In this article we are going to do a deep dive into working with WordPress user meta functions and understanding how the data is stored in the database. Our main goal is to build a complete guide on the WordPress user meta functions.
Here are the main topics that we’ll cover today:
- Detailed overview of the main WordPress user meta functions with examples
- How the different data types are stored in the database and returned
- Searching WordPress user meta
Now let’s get started!
WordPress User metadata functions
The functions that we’ll go through today are the ones that allow us to create, read, update and delete user meta data. Each of them has its specifics that are important to know when working with these functions. If we fail to call them correctly, we may end up with unexpected results, or even loosing some data. Now, let’s go through each of the functions.
As you may imagine, this function adds WordPress user meta fields. These fields can be used in plugins, profile pages, and plain information storage. This function can only add information though. Thus it won’t work for update operations.
The function can be called with the following parameters:
add_user_meta( (int) $user_id, (string) $meta_key, (mixed) $meta_value, (boolean) $unique = false );
Return values
The function will return the ID of the meta record created on success. Otherwise, it will return false .
The $unique parameter
The $unique parameter specifies whether there should be one value stored for this user field or multiple values are allowed. It defaults to false , which means that you can store multiple values for the specified user and meta key.
Let’s see some examples.
$res1 = add_user_meta(1, 'languages', 'English'); // $res1 is 20 $res2 = add_user_meta(1, 'languages', 'Italian'); // $res2 is 21
In this example we have added two meta values for the “languages” field of user 1. As you can see, we have left the $unique parameter blank, which means that it is set to false by default. In this way, we can add multiple values for this user field.
Both additions are executed successfully and the results of the commands contain the IDs of the created records. This is how the values are stored in the database:
Now, let’s try the same for user 2, but this time we’ll set $unique to true :
$res1 = add_user_meta(2, 'languages', 'English', true); // $res1 is 36 $res2 = add_user_meta(2, 'languages', 'Italian', true); // $res2 is false
With this example, the first line will be executed successfully and it will return the ID of the meta record. However, when we attempt to add another value on the second line, the value will not be added since uniqueness is enforced. And this is what we’ll have in the database after running this code:
This function works quite similarly to the add_user_meta function. The difference is that this function can be used to overwrite information as well. Therefore, if you want to add or edit the current user fields, this is a more flexible approach. One difference is that this function can be used to create custom user fields, but only once. If you run the add_user_meta 100 times, you have 100 entries. If you run the update function 100 times, you have just a single value.
The function can be called with the following parameters:
update_user_meta( (int) $user_id, (string) $meta_key, (mixed) $meta_value, (mixed) $prev_value = '' );
Return values
This function can have different outcomes depending on how it is called and the existing stored values. It returns:
- the ID of the meta record when a new record is created
- true when updating an existing record
- false when the update fails or when the existing value is the same as the updated one (e.g. there is no change in the value)
Let’s see a simple example of creating and updating a single value for a user and the results returned. We start with no existing meta value for the user 1. The first time we run the function there will be a new record created, since there was no existing record with this meta key for this user:
$res = update_user_meta(1, 'color_scheme', 'blue'); // $res is 38
This function call will return the ID of the new meta record. This is how the record looks in the database:
If we call the update_user_meta function one more time, but with a different value:
$res = update_user_meta(1, 'color_scheme', 'green'); // $res is true
This time the existing record will be updated with the value “green”. And the function will return true. Here is how the updated record looks in the database:
And if we execute the same code again with the same meta value:
$res = update_user_meta(1, 'color_scheme', 'green'); // $res is false
This time the function will return false, since there was no change in the value.
The $prev_value parameter
When the $prev_value parameter is specified, only the records with the specified value will be updated.
Let’s see an example. Let’s say that for the “color_scheme” field, user 1 has a value of “green” and user 2 has a value of “blue” as illustrated here:
If we then run the following code for both users, which updates the value to red only when the existing value is “green”:
$res1 = update_user_meta(1, 'color_scheme', 'red', 'green'); // $res1 is true $res2 = update_user_meta(2, 'color_scheme', 'red', 'green'); // $res2 is false
We will see that for user 1 the update will be executed successfully and it will return true. For user 2 though, the update will not be applied, since the current value is different than “green”, and therefore the function will return return false. This is the result of running this code:
The $prev_value parameter can also be used to update a single value when there are multiple records with the same meta key for the specified user.
To illustrate this, let’s use the example above where we have added two items for the “languages” meta key:
If we want to update just one of the values, we can use the following code:
$res = update_user_meta(1, 'languages', 'Spanish', 'Italian') // $res is true
And this is the result of the update in the database:
Here it is important to mention that with multiple meta values per meta key, if we omit the $prev_value parameter:
$res = update_user_meta(1, 'languages', 'Dutch'); // $res is true
All of the fields with this meta key will be updated for this user:
When it comes to WordPress user meta search and display, this is the function you need. This function is very flexible and the only required argument is the first one.
get_user_meta( (int) $user_id, (string) $meta_key = '', (boolean) $single = false );
Return values
This function can have various different outcomes depending on many factors:
- when the $single parameter set to true, the function will return the meta field value. If no value exists, it will return an empty string
- when the $single parameter set to false, the function will return an array of the existing values
- when $meta_key is blank, it will return an array of all of the existing meta fields for the specified user
That’s why it is important to understand how the get_user_meta function works in the different scenarios.
get_user_meta with single values
Let’s start with the following example, where we store one value per meta key. As you can see on the screenshot below, we have two different values stored for user 1 and user 2.
If we call the get_user_meta function by omitting the $single parameter, this parameter will default to false. This means that we are expecting this field to have multiple values and therefore the function will return an array, where the first element is the user value.
$res = get_user_meta(1, 'occupation'); // $res is array('Graphic Designer')
That’s why, if we expect this field to have a single value, we need to explicitly set the $single parameter to true:
$res = get_user_meta(1, 'occupation', true); // $res is 'Graphic Designer'
In this way, the result will be the single value as a string.
get_user_meta with multiple values
If the meta field can contain multiple values, then the $single parameter should be set to true. This is the default value, so we can omit this parameter in this case.
Let’s see an example where each user can have multiple values for the same field. As you can see on the screenshot below, user 1 has two values for this field:
If we run the following code, we’ll get all the values for this field of the user:
$res = get_user_meta(1, 'languages'); // $res is array('English', 'Italian')
If, however, we set the $single parameter to true, we’ll only get the first value:
$res = get_user_meta(1, 'languages', true); // $res is 'English'
get_user_meta with null values
It’s also important to understand what the function returns when there is no value stored for the specified user field. Again, this mainly depends on the $single parameter. When omitted (or set to false), it will return an empty array:
$res = get_user_meta(1, 'some_field'); // $res is array()
Otherwise, when set to true, it will return an empty string:
$res = get_user_meta(1, 'some_field', true); // $res is ''
get_user_meta with no meta_key specified
If you specify just the $user_id you get all WordPress user meta. All custom fields and values will be loaded as a single big array. For example, running the following code will load all of the user meta fields for user 1:
$res = get_user_meta(1);
The result will look like this:
array( 'nickname' => array('admin'), 'first_name' => array('John'), 'languages' => array('English', 'Italian'), ... )
Now the next element for custom field manipulation is the delete operation. This works very similarly to the update_user_meta function, in a sense that it tries to search for specific values. Therefore, if you specify which WordPress user meta value to delete, it deletes just that value. If you specify no value, this function deletes the entire meta key.
delete_user_meta( (int) $user_id, (string) $meta_key, (mixed) $meta_value = '' );
Return value
This function returns a boolean – true for successful deletion and false for failure.
The $meta_value parameter allows you to specify the value that the field to delete should contain. For example, the following code will delete all the meta fields with key “languages” for user 1. It doesn’t matter if there is one single value or multiple values, all of them will be deleted:
$res = delete_user_meta(1, 'languages');
If, however, we specify the $meta_value parameter, we can then delete specific values only. For example, if user 1 has these values stored for the “languages” field:
and we set the $meta_value parameter to ‘English’:
$res = delete_user_meta(1, 'languages', 'English'); // $res is true
only the record with value ‘English’ will be deleted and the function will return true:
If there is no field with the value specified in the $meta_value paramter, no records will be deleted and the function will return false.
$res = delete_user_meta(1, 'languages', 'Inexisting value'); // $res is false
How the different data types are stored in the database and returned
The meta_value table column in the database is from type “longtext”, which means that it can only store strings. Therefore, booleans, numbers, and strings are all stored as strings. Arrays are stored as serialized strings. Some of these values are returned in the format they are stored. Others are processed by WordPress and returned in their original PHP data type. That’s why, in order to avoid errors it is important to understand how everything works. Let’s go through each of the main data types.
Booleans
Boolean true is stored as string “1” in the database. false is stored as an empty string.
Therefor running the following code:
add_user_meta(1, 'premium_user', true); add_user_meta(2, 'premium_user', false);
Will create the following records:
and when loading the data with get_user_meta, the values are returned in the same format as stored in the database.
$res1 = get_user_meta(1, 'premium_user', true); // $res1 is "1" $res2 = get_user_meta(2, 'premium_user', true); // $res2 is ""
So, to make sure that you will be working with actual boolean values, you will need to type cast the results:
$res1 = (boolean)get_user_meta(1, 'premium_user', true); // $res1 is true $res2 = (boolean)get_user_meta(2, 'premium_user', true); // $res2 is false
Numbers
Numbers are converted to strings as well. Therefore the following code:
add_user_meta(1, 'orders', 0); add_user_meta(2, 'orders', 1);
will store the values as “0” and “1” in the database respectively:
$res1 = get_user_meta(1, 'orders', true); // $res1 is "0" $res2 = get_user_meta(2, 'orders', true); // $res2 is "1"
So, again typecasting is recommended to make sure that we are working with actual numbers. You can type cast to int or float depending on the type of the numbers stored:
$res1 = (int)get_user_meta(1, 'orders', true); // $res1 is 0 $res2 = (int)get_user_meta(2, 'orders', true); // $res2 is 1
Arrays
Arrays are stored as a PHP serialized string in the database.
Let’s see an example. Here we’ll create a meta field with an array value. Each value of the array will be from a different data type, so we can illustrate how this stored and later processed.
$value = array('green', 1, true); add_user_meta(1, 'details', $value);
And this is how this value looks in the database:
This time, however WordPress does the data formatting for us when loading the data with the get_user_meta function and returns the result as an array:
$res = get_user_meta(1, 'details', true); // $res is array('green', 1 ,true)
Here you can notice that the format of the values in the array is preserved.
Null values
Null values are stored as NULL in the database. This is great, because we won’t need to do any type casting.
For example, after running the following code:
add_user_meta(1, 'address', null);
The record will be created like this in the database:
And when loading the value, the result is returned as null as well:
$res = get_user_meta(1, 'address', true); // $res is null
Managing and searching user meta
In case you don’t want to write code, it’s possible to use a plugin to manage WordPress user meta. With Users Insights, you can add custom fields, edit their values and get users based on the custom user fields. For more information, head over to our detailed guide on the Managing custom user meta fields.
The Custom Fields can be used to create new fields or manage existing user meta fields. You can map existing custom fields under Users Insights > Custom fields. There you can set the custom field type (text, date, number, dropdown). If you are adding these fields with a plugin, for example, you can search now users based on these values. In our How to display, search and filter WordPress user meta data article, we have described the process in more detail. However, let’s go through a few examples:
Let’s say you have a custom meta field that stores number of orders for each user. If you map this custom field as a number type, these are the filtering options you get:
These options differ from the regular text type, which has these options:
- Contains/does not contain
- Is/is not
- Starts/Ends with
Then you can filter users with more than one order for example:
The date type has different options as well. For instance, if you have a custom field for date of birth, then you can filter users based on different parameters for it:
Conclusion
Today we looked into different WordPress functions to manage WordPress user metadata. These functions are the get_user_meta, add_user_meta, delete_user_meta and update_user_meta. In addition, we investigated the internal differences in the $unique and $single parameters. Furthermore, we explored how the different data types are stored, and how to correctly get this information.