How to store multiple input values with same meta_key
Question
is there a way to store the input value from multiple custom meta box fields with the same meta_key
?
I use the following code to store ONE value for the meta_key
'startdate':
function startdate() {
global $post;
$custom = get_post_custom($post->ID);
$startdate = $custom["startdate"][0];
?>
<label>Startdate</label><br/>
<input type="text" name="startdate" value="<?php echo $startdate; ?>"/>
<?php }
add_action('save_post', 'save_details');
function save_details(){
global $post;
update_post_meta($post->ID, "startdate", $_POST["startdate"]);
}
If i had a second input field, how can i store its value with a different meta_id
but the same meta_key
(startdate)? Thank you very much!
(If i use the built-in custom field functionality i can save multiple values for the same meta key...)
Solution
Change your form as suggested:
function startdate() {
global $post;
$custom = get_post_custom($post->ID);
echo "<label>Startdates</label><br/>";
for ($i=0; $i<count($custom["startdate"]);$i++) {
echo "<input type=\"text\" name=\"startdate[".$i."]\" value=\"".$custom["startdate"][$i]."\" />";
}
}
You'll have to remove and reinstate your individual postmeta entries:
add_action('save_post', 'save_details');
function save_details($post_id) {
if ($parent_id = wp_is_post_revision($post_id)) $post_id = $parent_id;
if (!empty($_POST['startdate']) && is_array($_POST['startdate'])) {
delete_post_meta($post_id, 'startdate');
foreach ($_POST['startdate'] as $startdate) {
add_post_meta($post_id, 'startdate', $startdate);
}
}
}
Then, of course, you'll need to add some sort of add/remove mechanism to your metabox form, probably through JS.
OTHER TIPS
As mentioned by t31os try changing your form inputs to use name="startdate[]"
then loop through the array saving each value:
foreach ($_POST["startdate"] as $datevalue) {
update_post_meta($post->ID, "startdate", $datevalue);
}