1

I see when I do a get_user_meta($id, 'key') that the results is an array.

I also see in the documentation that I can do update_user_meta($id, 'key', $value, $prev_value) which is meant to "differentiate between meta fields with the same key and user ID". I'm reading that as meaning I could do several updates to the same $user+$key and have them appear as extra entries in the array that get_user_meta returns.

Like so:

update_user_meta ($id,'key', 'first', 'first');
update_user_meta ($id,'key', 'second', 'second');
update_user_meta ($id,'key', 'third', 'third');
echo "<pre>";
print_r(get_user_meta($id, 'key'));

I expected results like this:

Array
(
   [0] => first
   [1] => second
   [2] => third
)

But instead all I get is

 Array
 (
   [0] => first
 )

I suspect I might be misunderstanding what $prev_value is for.

Now, I know I can store an array in a meta field (update_user_meta($id,'key',$array)), and/but that shows up as an array within an array (i.e. get_user_meta($id,'key')[0] would be $array).

Array
(
  [0] => Array
         (
           [0] => first
           [1] => second
           [2] => third
         )
)

Where I'm leading to is being able to do a get_users query and search for one particular value which is in $array.

$users = get_users( 
           array(
             'meta_query' => array( array(
               'key' => 'change-dates',
               'value' => '2018-02-27T07:49',
               'compare' => '='
             ),
             'fields' => array('ID','display_name')
           )
         );

When I do that get_users with update_user_meta($id,'key',$array), I get nothing. My assumption is that wp is searching the multiple values of get_user_meta, but since there is only 1 and it's not a string (it's an array of dates), it's giving a big nope.

TL;DR:

I want to store an bunch of dates in the user-meta field 'changes-dates', and then be able to do various searches on those individual values.

My whole approach might be wrong.

  • to add new values, you need to use codex.wordpress.org/Function_Reference/add_post_meta – mmm Mar 19 '18 at 6:47
  • @mmm hmm ... these are users I want to add the meta fields to, not posts. Wait ... add_post_meta ? Oh, there's an add_user_meta too … brb … – Erics Mar 19 '18 at 8:40
  • 1
    yes sorry it's add_user_meta. and there is the same use with add_term_meta and add_comment_meta if a futur reader of this question needs it. – mmm Mar 19 '18 at 9:03
  • 1
    A bit of fiddling, and it's working, including the searching! Thanks @mmm for the tip in the right direction. Write an answer if you want. – Erics Mar 19 '18 at 10:30

Your Answer

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

Browse other questions tagged or ask your own question.