adrian proscinski
adrian proscinski

Reputation: 21

Wordpress: array_push creates array inside the previous array

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)
}

Upvotes: 0

Views: 515

Answers (1)

Xhynk
Xhynk

Reputation: 13880

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 );
}

Upvotes: 2

Related Questions