0

I want to create a new user meta that contains array content How can i do this ?

Another question : is it true using this code to check if the array user meta exists before creating it ?

<?php
$key = 'add_me';
$user_id= get_current_user_id();
$themeta = get_user_meta($user_id , $key, TRUE);
if($themeta != '') {
// code 
}
?>
1

As noted at the codex page for get_user_meta():

NOTE
If the meta value does not exist and $single is true the function will return an empty string. If $single is false an empty array is returned.

So I would suggest to do the check like this:

! empty( $themeta )

Regrading your other question, you can save the array by simply doing it like below:

$the_meta_array = array (
    'key-1' => 'value-1',
    'key-2' => 'value-2',
);  
$user_id = 12345;  
$user_meta_key = 'your-key';  
add_user_meta( $user_id, $user_meta_key, $the_meta_array );

Which is enough to save your array to the users meta data. add_user_meta() is just a wrapper for add_metadata(), the later uses maybe_serialize(), so your array will be saved as serialized string.

One more note about getting back the array you saved. You use get_user_meta(), which is just a wrapper for get_metadata(), the later uses maybe_unserialize(), so an array will be returned. But you probably want to do this with $single set to true when retrieving the meta data later on. Because the default value of the $single parameter is false:

$single
(boolean) (optional) If true return value of meta data field, if false return an array. This parameter has no effect if $key is left blank.
Default: false

$user_id = 12345;  
$user_meta_key = 'your-key'; 
$single = true;   
$retrieved_meta_array = get_user_meta( $user_id, $user_meta_key, $single );

If you don't use true you will get back your array wrapped inside an additional array, as above cite does suggest, which you are most likely don't want, because the array you saved is in this case actually the single value you want to return - ergo setting $single to true is the way to do it.

  • My pleasure! @SufyanHassan – Nicolai Jan 9 '15 at 22:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.