将类似的metabox字段保存到数组中


Wordpress - save similar metabox fields into array

我需要保存为具有相同键的数组值。例如,对于select name 'crop43',我需要保存两个值:vertical和horizontal。

metabox中的输入字段:

<p>
<label for="crop43">4:3 Crop position</label>
<select name="crop43[]" style="width: 10%">
    <option>Center</option>
    <option>Top</option>
    <option>Bottom</option>
</select>
<select name="crop43[]" style="width: 10%">
    <option>Center</option>
    <option>Left</option>
    <option>Right</option>
</select>
</p>

保存过程:

if(isset($_POST['crop43'])) {
    update_post_meta($post->ID, 'crop43', $_POST['crop43']);
}

它只保存最后的信息(水平位置),但不保存垂直位置

一个更简单的解决方案是重命名两个选择。

<p>
<label for="vertical">4:3 Crop position</label>
<select name="vertical" style="width: 10%">
    <option>Center</option>
    <option>Top</option>
    <option>Bottom</option>
</select>
<select name="horizontal" style="width: 10%">
    <option>Center</option>
    <option>Left</option>
    <option>Right</option>
</select>
</p>

你可以这样做:

if(isset($_POST['horizontal'] && isset($_POST['vertical]){
$array = array();
$array['horizontal'] = $_POST['horizontal'];
$array['vertical'] = $_POST['vertical'];
$crop43 = json_encode($array);
update_post_meta($post->ID, 'crop43', $crop43);
}

然后,当您想要将数据库值更改回数组时,使用json_decode