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?
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: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 ofupdate_metadata()
which takes the ID + the value and puts it into the database as and array.I had the same problem. Adding “true” to “get_user_meta” worked for me. For example:
FROM:
TO:
Had the same issue and resolved it with this little bit, which puts all new values in a single array saved as the user meta data:
Array before save/update for meta key (from get_user_meta):
Resulting Array (after meta update) adding value of ‘access_5’:
If you need the new value to be added to the end of the array, do this instead:
Then update the meta…
Bryan
It seemed that the problem was with serializing/unserializing the array, so I just rewrote the function to be a comma sperated string:
Shaun’s answer was correct but I feel needs more clarification. You can put in an array into a user meta entry but when you retrieve it you still need to retrieve it with the single argument set to true or else you get an array of an array back. Here is my code: