我正在构建简单的表单
的template.php
<div class="form-group relocate">
<label for="contact_method"><?php _e('Best Contact Method', 'jobboard') ?></label>
<?php
$contact_method = get_post_meta($resume_id, 'resume_contact_method', false);
// $contact_method = explode( ',', $contact_method );
var_dump($contact_method);
?>
<ul>
<li class="checkbox-inline">
<input type="checkbox" id="resume_contact_method" name="resume_contact_method[]" value="email" <?php if($contact_method){echo (in_array('email', $contact_method)) ? 'checked="checked"' : ''; } ?>><label for="resume_contact_method_email"><?php _e( 'Email', 'jobboard' ); ?></label>
</li>
<li class="checkbox-inline">
<input type="checkbox" id="resume_contact_method" name="resume_contact_method[]" value="phone" <?php if($contact_method){echo (in_array('phone', $contact_method)) ? 'checked="checked"' : ''; } ?>><label for="resume_contact_method_phone"><?php _e( 'Phone', 'jobboard' ); ?></label>
</li>
</ul>
</div>
function.php
for($i=0; $i<sizeof($_POST['resume_contact_method']); $i++){
update_post_meta( $resume_id, 'resume_contact_method', $_POST['resume_contact_method'][$i] );
}
我的代码问题,如果我尝试保存数据复选框,表单输入只保存最后点击的数据。谁能告诉我哪里犯了错误?
答案 0 :(得分:0)
Instead of using update_post_meta. Use the delete_post_meta and add_post_meta.
if (!empty($_POST['resume_contact_method']) && is_array($_POST['resume_contact_method'])) {
delete_post_meta($resume_id, 'resume_contact_method');
foreach ($_POST['resume_contact_method'] as $resume_contact_method_kv) {
add_post_meta($resume_id, 'resume_contact_method', $resume_contact_method_kv);
}
}
Refer here working example with more details about storing multiple values under the single meta key recommended way :