Created
June 11, 2014 13:46
-
-
Save brettshumaker/16aa67075489dd5b1dac to your computer and use it in GitHub Desktop.
WordPress - storing array of values in custom post type custom meta field
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// This is essentially what I have adding the post meta field, not doing this from the edit post screen. | |
$name_meta['first-name'] = "Joe"; | |
$name_meta['middle-name'] = "D."; | |
$name_meta['last-name'] = "Schmoe"; | |
$name_meta['suffix'] = "Jr."; | |
update_post_meta($post->ID, '_staff_member_name', $name_meta); | |
// update_post_meta automatically serializes the array when adding it to the database | |
?> | |
<?php | |
// Here, I'm pulling the data. | |
$stored_name_array = get_post_meta($post->ID, '_staff_member_name', true); | |
// get_post_meta automatically unserializes the data. Adding 'true' returns just the inner array. | |
print_r($stored_name_array); | |
// This returns: | |
// Array ( [\'first-name\'] => Joe [\'middle-name\'] => J. [\'last-name\'] => Schmoe [\'suffix\'] => Jr. ) | |
// Why are there escaped single quotes in the array keys? I've never seen this before. | |
foreach ($stored_name_array as $key => $value) { | |
$stored_name_array[str_replace("'", '', stripslashes($key))] = $value; | |
unset($stored_name_array[$key]); | |
} | |
print_r($stored_name_array); | |
// This returns: | |
// Array ( [first-name] => Joe [middle-name] => J. [last-name] => Schmoe [suffix] => Jr. ) | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment