1

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..

6

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_names, 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

| improve this answer | |
  • Fantastic! I wasn't so much asking if it was possible, but more asking if it was considered a reasonable practice. Thank you kindly! – dcolumbus May 31 '14 at 5:14
  • Well it's certainly a common enough occurrence that the core WP contributors thought it reasonable to include support for it ;) . In general I would say this is a perfectly reasonable solution for most problems in this scope, but if you're working with much larger objects/amounts of data it would probably be prudent to create your own database table to store it, so as to avoid the overhead associated with meta-data. – bosco Jun 1 '14 at 17:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.