WordPress post meta nesting arrays instead of adding to array

I am struggling with something that I thought would be simple. Retrieve a post meta array, search it and add to it. The search never finds a user if they have been added and from what I can see the meta key value ends up being an increasingly nested multidimensional array.

// Get post ID
$id = get_the_ID();

// Get array of signed up users
$users_signed_up = get_post_meta($id, 'users_signed_up', false);

// Get the user ID
$user_id = get_current_user_id();

// Search retrieved array
if (!in_array($user_id, $users_signed_up)) {

    // Add user to array
    array_push($users_signed_up, $user_id);

    // Add array back to post meta
    update_post_meta($id, 'users_signed_up', $users_signed_up);
}

var_dump of users_signed_up with a couple of users added by avoiding the in_array search.

Read More
array(1) { [0]=> array(2) { [0]=> array(2) { [0]=> array(1) { [0]=> int(32) } [1]=> int(36) } [1]=> int(1) } } 

However what I expect it to look like is this.

array(3) { [0]=> int(1) [1]=> int(32) [2]=> int(36) } 

Related posts

1 comment

  1. $users_signed_up = get_post_meta($id, 'users_signed_up', true);
    
    if (!in_array($user_id, $users_signed_up)) {
    
        // Add user to array
        $users_signed_up[]= $user_id;
    
        // Add array back to post meta
        update_post_meta($id, 'users_signed_up', $users_signed_up);
    }
    

    should do it assuming the original array is correct

Comments are closed.