WordPress: handling user meta

WordPress: handling user meta

How to handle user meta in WordPress.

We're usually accustomed to store the metadata associated to WordPress posts and pages by using the update_post_meta() function. This of course works for posts but what about WordPress users? WordPress already provides a series of fields in each user's profile. These fields, however, fall short when it comes to associate other types of values to user, for example their orders or their preferences about the contents of our site.

The update_user_meta() function accepts as its only mandatory parameter the user ID, followed by a key ( the name of our user meta field ) and a value ( the value of our user meta field as a string ):


global $current_user;
get_currentuserinfo();

$user_id = $current_user->ID;
$age = $_POST['age'];
$date_of_birth = $_POST['date-of-birth'];

// Validation here

update_user_meta( $user_id, 'age', $age );
update_user_meta( $user_id , 'date_of_birth', $date_of_birth );

We can retrieve our values by using the get_user_meta() function:


global $current_user;
get_currentuserinfo();

$user_id = $current_user->ID;

$age = get_user_meta( $user_id, 'age', true );
$date_of_birth = get_user_meta( $user_id , 'date_of_birth', true );

The third parameter of this function is set here to true. This tells WordPress to return a single value and not an array, which is the default behavior.

What if we want to store multiple parameters? In this case, we need to serialize them before saving them in the user's meta field:


global $current_user;
get_currentuserinfo();

$user_id = $current_user->ID;

$values = array(
	'age' => $_POST['age'],
	'date-of-birth' => $_POST['date-of-birth'],
	'gender' => $_POST['gender'],
	'phone' => $_POST['phone'],
	'mobile' => $_POST['mobile']

);

// Validation here

$meta = serialize( $values );
update_user_meta( $user_id , 'my-user-data', $meta );

And if we want to get them back:


global $current_user;
get_currentuserinfo();

$user_id = $current_user->ID;

$meta = get_user_meta( $user_id, 'my-user-data', true );
$values = unserialize( $meta );

This approach is also used internally by WordPress to store settings and preferences.

References