I am writing a function that adds an ID number to an array and puts the array in the usermeta. $_GET['auction']
is the post_id
.
Below is the function:
$reminders = get_user_meta( $current_user->ID, "reminders" );
print_r( $reminders );
if( in_array( $_GET['auction'], $reminders ) ) {
echo "Failed: Auction already in list";
} else {
array_push( $reminders, intval( $_GET['auction'] ) );
if ( update_user_meta( $current_user->ID, "reminders", $reminders ) ) {
echo "Success";
} else {
echo "Failed: Could not update user meta";
}
}
print_r( $reminders );
Here is the output after adding one auction:
Array ( )
Success
Array ( [0] => 7 )
Here is the output after adding two auctions:
Array ( [0] => Array ( [0] => 7 ) )
Success
Array ( [0] => Array ( [0] => 7 ) [1] => 73 )
And here is the output after adding three auctions:
Array ( [0] => Array ( [0] => Array ( [0] => 7 ) [1] => 73 ) )
Success
Array ( [0] => Array ( [0] => Array ( [0] => 7 ) [1] => 73 ) [1] => 0 )
Notice that adding a new element to the array using array_push
works fine. But when the array is stored in the usermeta then retrieved again, the last element in the array has been put into an array of its own, creating an infinitely dimensional array. I’d prefer to keep this array one dimensional.
Is there a way I can run update_user_meta
and get_user_meta
without it changing the structure of my array?
5 s
Haven’t used the function for quite a time, but i guess your problem is that you are pushing an array into an array. So check if intval($_GET['auction'])
is an array:
echo '<pre>';
print_r(intval($_GET['auction']));
echo '</pre>';
Edit #1: You maybe need to get the value from that array and then array_push it. So maybe something like array_push( $reminders, $_GET['auction'][0]) );
– if you’re only adding one single value. You could also do something like $reminders[] = $_GET['auction'][0];
to add it to the end of your array.
Edit #2: From a look at the core file: yes. update_user_meta()
is just an alias of update_metadata()
which takes the ID + the value and puts it into the database as and array.
// From /wp-includes/meta.php ~ line 135
$where = array( $column => $object_id, 'meta_key' => $meta_key );
if ( !empty( $prev_value ) ) {
$prev_value = maybe_serialize($prev_value);
$where['meta_value'] = $prev_value;
}