Storing PHP Arrays in Wordpress User Meta Database
You need to set the last parameter from false
to true
:
$wp_user_film_prefs_arr = get_user_meta( $wp_user_id, $wp_user_film_prefs_key_label, true );
That third parameter is $single
:
(boolean) (optional) If true return value of meta data field, if false return an array.
Default: false
That might sound contra-productive in your eyes, but the meta data field can contain multiple values. In your case you don't need that, but the single value. The single value is your array.
See as well: get user meta
Codex
chuuke
Updated on June 05, 2022Comments
-
chuuke almost 2 years
This should be easy for a PHP expert. I am having trouble storing and pulling arrays in Wordpress through the update_user_meta function.
So I have an associative array built like so:
Array ( [film_genres] => Array ( [action] => 50 [comedy] => 50 [crime] => 50 [documentary] => 50 [drama] => 50 [family] => 50 [horror] => 50 [romantic] => 50 [sci-fi] => 50 [thriller] => 50 ) [film_types] => Array ( [blockbuster] => 0 [independent] => 0 ) [film_eras] => Array ( [1920s_1940s] => 0 [1950s_1960s] => 0 [1970s_1980s] => 0 [1990s_2000s] => 0 [post_2010] => 0 [pre_1920s] => 0 ) [last_updated] => 2011-10-12 21:21:28 )
But when I go to update this data in the user meta table via:
update_user_meta( $user_id, $meta_key, $meta_value, $prev_value )
The data gets put in the db properly, but when i call the data back and print the new array to screen, it has a nested array key of [0] within the array, like this:
Array ( [0] => Array ( [film_genres] => Array ( [action] => 50 [comedy] => 50 [crime] => 50 [documentary] => 50 [drama] => 50 [family] => 50 [horror] => 50 [romantic] => 50 [sci-fi] => 50 [thriller] => 50 ) [film_types] => Array ( [blockbuster] => 0 [independent] => 0 ) [film_eras] => Array ( [1920s_1940s] => 0 [1950s_1960s] => 0 [1970s_1980s] => 0 [1990s_2000s] => 0 [post_2010] => 0 [pre_1920s] => 0 ) [last_updated] => 2011-10-12 21:21:28 ) )
How can I get it to store the array exactly like my first array? I am pulling the meta value array via the WP command:
$wp_user_film_prefs_arr = get_user_meta( $wp_user_id, $wp_user_film_prefs_key_label, false );
Is there something I'm doing wrong? Thanks in advance!!!
-
chuuke over 12 yearsYep, you were right! I initially chose false thinking that it it would then return the array, as in my array of values, but it's retruning an array OF the meta data field. Changed to true to return the value and then stored it as an array with "maybe_unserialize($wp_user_film_prefs_val);" Thanks man!
-
James over 11 yearsWordPress does the serialization for you behind the scenes. @harkra had the correct answer.
-
henrywright about 10 yearsIt's hard to get your head around thinking of an array as a single value
-
Maciej Krawczyk about 6 yearsIt sure is a poor api design, thanks for your answer!