【问题标题】:Checkbox can't storing multiple value复选框不能存储多个值
【发布时间】:2017-01-08 21:08:11
【问题描述】:

我正在构建简单的表单

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] );   
}

我的代码问题,如果我尝试保存数据复选框,表单输入只是保存最后点击的数据。谁能告诉我哪里做错了?

【问题讨论】:

  • 1.您不能在多个元素上拥有相同的 ID...ID 对于每个实际元素都是唯一的。 2.将名字改成name="resume_contact_id"(去掉[],在你使用的方式复选框上不需要)。
  • @MagnusEriksson 它仍然只保存最后一次点击,无法保存多个数据
  • 您正在遍历结果并在每次迭代中用新结果替换“resume_contact_method”-meta 字段中的值,因此只有最后一个复选框值被保存。删除你的循环并保存$_POST['resume_contact_method'],它应该被保存为一个数组。

标签: php wordpress


【解决方案1】:

而不是使用 update_post_meta。使用 delete_post_meta 和 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);
    }
}

请参阅此处的工作示例,其中包含有关在单个元键推荐方式下存储多个值的更多详细信息:

https://wordpress.stackexchange.com/questions/10821/how-to-store-multiple-input-values-with-same-meta-key

【讨论】:

  • 这不会给他与使用 update_post_meta($resume_id, $_POST['resume_contact_method']) 相同的结果,但是在这种情况下,使用三个 DB 查询(一个删除和两个插入)而不是一个(更新)?
  • 您的意思是update_post_meta($resume_id, $_POST['resume_contact_method']) 比删除和添加效果更好?
猜你喜欢
  • 2016-02-20
  • 1970-01-01
  • 1970-01-01
  • 2015-09-02
  • 1970-01-01
  • 1970-01-01
  • 2017-04-19
  • 2016-04-22
  • 1970-01-01
相关资源
最近更新 更多