0

I want to create in WordPress usermeta data on array() with user favorite posts who he can add to this meta favorite.

If I use array_push() on get_user_meta() the array is nested in subsequent array.

my_operation(){    
   $meta_user_favorite = get_user_meta($user_id,"favorite");   
   array_push($meta_user_favorite, $post_id);    
   update_user_meta( $user_id, "favorite", $meta_user_favorite);  
}

After several such operations it's my result in var_dump($meta_user_favorite);

array(1) {
  [0]=>
  array(2) {
    [0]=>
    array(2) {
      [0]=>
      array(2) {
        [0]=>
        array(1) {
          [0]=>
          int(726)
        }
        [1]=>
        int(713)
      }
      [1]=>
      int(710)
    }
    [1]=>
    int(688)
  }
}

It should be in one array, what I'm doing wrong?

array(1) {
      [0]=>int(726)
      [0]=>int(713)
      [0]=>int(710)
      [0]=>int(688)
}
1
  • $meta_user_favorite = array_merge($meta_user_favorite, $post_id); ? Commented Mar 5, 2019 at 16:32

1 Answer 1

2

Take a look at the docs for get_user_meta(). The third argument, which you're omitting, is $single, which defaults to false, and determines whether to return an array or the value. If you pass true to that (which honestly, I use in 95% of my use-cases when dealing with user and post meta), it should work.

my_operation(){
    $meta_user_favorite = get_user_meta( $user_id, 'favorite', true );   
    array_push( $meta_user_favorite, $post_id );    
    update_user_meta( $user_id, 'favorite', $meta_user_favorite );
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! I had the same issue and now it's resolved. This should be marked as the accepted answer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.