Currently, I am adding user metadata with the key position_name
and a string value representing a user’s position, such that I can retrieve a user’s position by way of a call similar to:
$position = get_user_meta(22, 'position_name', true);
This works perfectly for one position per user, but I’d like to be able to associate each user with several positions. Would adding a serialized array within the position_name
field be an appropriate way of achieving this?
I hope that makes sense..
1 Answer
If you check out the documentation for the update_user_meta()
function, you’ll note that the $meta_value
parameter already accepts objects and arrays, so you can simply save a user’s positions in an array without any additional effort:
update_user_meta(
22,
'position_names',
array(
'Khaleesi of the Great Grass Sea',
'Breaker of Chains',
'Mother of Dragons'
)
);
The user meta functions already take care of serializing and unserializing the array for you (converting it to and from a string, respectively). Note that the documentation for get_user_meta()
specifies that the last parameter $single
denotes whether to just return one meta-value directly, or return all values in an array. You’re looking to get all of the position_name
s, so you should pass false
as $single
or omit the argument entirely (in which case it will default to false
):
$position_names = get_user_meta( 22, 'position_names' );
//$position_names[0] === 'Khaleesi of the Great Grass Sea'
//$position_names[1] === 'Breaker of Chains'
//$position_names[2] === 'Mother of Dragons'
Note
If you use
update_user_meta()
in the future to store an object (or an associative array), know that you may run into bug #9640