Let’s analyze your code and what it does.
Assuming that the current fruits stored in the database are ‘pineapple’ and ‘orange’, get_user_meta(2, 'fruits', false)
will return something like this:
array( array( 'pineapple', 'orange' ) )
This is because you passed false
as the third argument, $single
. The function returns an array if $single
is false
and the value of the meta data field if $single
is true
(docs). That is because there could be multiple fruits
entries in the database, so WordPress would return all of them if not explicitly told not to.
Since you only have one meta key storing all your fruits, we don’t want a list of all entries. Setting $single
to true
will result in this:
array( 'pineapple', 'orange' )
Let’s combine this with your $data
array:
$data = array(
get_user_meta(2, 'fruits', false),
'apple',
'pear',
'peach'
);
// results in: array( array( array( 'pineapple', 'orange' ) ), 'apple', 'pear', peach' )
$data = array(
get_user_meta(2, 'fruits', true),
'apple',
'pear',
'peach'
);
// results in: array( array( 'pineapple', 'orange' ), 'apple', 'pear', peach' )
Still not ideal! What you want is one single array containing all fruits. That means you need to merge these arrays:
$data = array_merge(
get_user_meta(2, 'fruits', true),
array(
'apple',
'pear',
'peach'
)
);
// results in: array( 'pineapple', 'orange', 'apple', 'pear', peach' )
Now, we can finally update the user meta accordingly:
update_user_meta(2, 'fruits', $data , false);
Here’s another false
at the fourth position. What does it mean? It’s the $prev_value
argument. If specified, the function only updates existing metadata entries with the specified value. Otherwise, it updates all entries (docs). Passing false
is the same as not specifying anything.
But what if we passed $prev_value
? Let’s have a look!
update_user_meta( 2, 'fruits', $data , array( 'pineapple', 'orange' ) );
// does update, because that's what's in the database.
update_user_meta( 2, 'fruits', $data );
// does update as well
update_user_meta( 2, 'fruits', $data , array( 'cherry', 'banana' ) );
// does not update, because that's not what is in the database.
In your case, I’d simply use update_user_meta( 2, 'fruits', $data );
because WordPress automatically turns it into the third example.
Let’s get our updated data from the database again! Remember, you don’t want an array of entries, so we use get_user_meta( 2, 'fruits', true )
get_user_meta(2, 'fruits', false);
// results in array( 'pineapple', 'orange', 'apple', 'pear', peach' )
That’s it!