Updating user meta data in WordPress using update_user_meta
The WordPress update_user_meta
function is used to update the metadata of a user in the WordPress database. This function can be useful for updating user-specific information such as custom fields, preferences, or any other additional data associated with a user.
By using the update_user_meta
function, developers can easily modify and update user metadata without directly manipulating the WordPress database. This provides a convenient and secure way to manage user-specific data within WordPress.
Parameters accepted by the WordPress update_user_meta function
$user_id
(int, required): User ID.$meta_key
(string, required): Metadata key.$meta_value
(mixed, required): Metadata value. Must be serializable if non-scalar.$prev_value
(mixed, optional, default: ”): Previous value to check before updating. If specified, only update existing metadata entries with this value. Otherwise, update all entries.
Value returned by the WordPress update_user_meta function
The function returns an int
if the key didn’t exist, true
on successful update, and false
on failure or if the value passed to the function is the same as the one that is already in the database.
Examples
How to update user meta with a single value
Use the update_user_meta
function to update a specific meta key for a user.
$user_id = 123;
$meta_key = 'favorite_color';
$meta_value = 'blue';
update_user_meta( $user_id, $meta_key, $meta_value );
How to update user meta with multiple values
Use the update_user_meta
function to update multiple meta keys for a user.
$user_id = 123;
$meta_values = array(
'favorite_color' => 'blue',
'hobby' => 'hiking'
);
foreach ( $meta_values as $key => $value ) {
update_user_meta( $user_id, $key, $value );
}
How to update user meta with conditional logic
Use the update_user_meta
function with conditional logic to update a meta key based on a certain condition.
$user_id = 123;
$age = 25;
if ( $age > 18 ) {
update_user_meta( $user_id, 'is_adult', true );
} else {
update_user_meta( $user_id, 'is_adult', false );
}
Conclusion
In conclusion, the update_user_meta
function is a valuable utility for developers working with user data in WordPress. By using this function, developers can easily update and manage custom user meta fields, providing a seamless experience for both users and administrators. With its flexibility and ease of use, update_user_meta
is a valuable addition to any developer’s toolkit when working with user data in WordPress.