2016-03-15 74 views
0

有了這個代碼,所選擇的選項被保存到數據庫:爲什麼不將選項保存到數據庫?

<select name="menu-item-visibility[<?php echo $item_id; ?>][]" id="edit-menu-item-visibility-<?php echo $item_id; ?>" class="chzn-select" multiple="true" 
    <option value="US" <?php $val = get_post_meta($item_id, 'locations', true); if (is_array($val)) { if (in_array("US", $val)) { echo "selected='selected'"; } else { echo ""; } } ?> >United States</option> 
    <option value="TH" <?php $val = get_post_meta($item_id, 'locations', true); if (is_array($val)) { if (in_array("TH", $val)) { echo "selected='selected'"; } else { echo ""; } } ?> >Thailand</option> 
    ... 
</select> 

有了這個代碼,他們是不是:

<select name="menu-item-visibility[<?php echo $item_id; ?>][]" id="edit-menu-item-visibility-<?php echo $item_id; ?>" class="chzn-select" multiple="true" data-placeholder="Select Countries"> 
<?php 
$countries = array('US' => 'United States', "TH" => "Thailand"); 
$vals = get_post_meta($item_id, 'locations', true); 
foreach($countries as $key => $value) { 
?> 
    <option value="<?php echo $key;?>" 
    <?php echo (is_array($vals) && in_array($key, $vals)) ? "selected='selected'" : ''; ?> > 
    <?php echo $value;?> 
    </option> 
<?php 
} 
?> 
</select> 

爲什麼不呢?

這是選擇如何發送到數據庫:

/* Put locations in the database. */ 
function csmi_update_locations($menu_id, $menu_item_db_id, $args) { 
    $meta_value = get_post_meta($menu_item_db_id, 'locations', true); 
    if (isset($_POST[ 'menu-item-visibility' ][ $menu_item_db_id ])) { 
     $new_meta_value = $_POST[ 'menu-item-visibility' ][ $menu_item_db_id ]; 
     if (!isset($new_meta_value)) { 
      delete_post_meta($menu_item_db_id, 'locations', $meta_value); 
     } 
     elseif ($meta_value !== $new_meta_value) { 
      update_post_meta($menu_item_db_id, 'locations', $new_meta_value); 
     } 
    } 
} 

這裏的要求,在查看源代碼的HTML。

<p class="field-visibility description description-wide"> 
... 
    <select name="menu-item-visibility[4][]" id="edit-menu-item-visibility-4" class="chzn-select" multiple="true" data-placeholder="Select Countries"> 
     <option value="US" > United States </option> 
     <option value="TH" > Thailand </option> 
    </select> 
</p> 
+0

你能分享你的代碼的一部分,它保存數據到數據庫? – pes502

+0

當然,會添加它。 – j8d

+1

試試這個

回答

0

請使用這樣的:

<select name="menu-item-visibility[<?php echo $item_id; ?>][]" id="edit-menu-item-visibility-<?php echo $item_id; ?>" class="chzn-select" multiple="true" data-placeholder="Select Countries"> 
<?php 
$countries = array('US' => 'United States', "TH" => "Thailand"); 
$vals = get_post_meta($item_id, 'locations', true); 
foreach($countries as $key => $value) { 
?> 
    <option value="<?php echo $key;?>" 
    <?php echo (is_array($vals) && in_array($key, $vals)) ? "selected='selected'" : ''; ?> > 
    <?php echo $value;?> 
    </option> 
<?php 
} 
?> 
</select> 
+0

你錯過了雙值引號value value =」<?php echo $ key;?>「 –

+0

Hi Atif,這是相同或不帶引號:/ – j8d

+0

你檢查你的複選框的HTML什麼是HTML? –

0

嗯,這是令人尷尬的。問題出在我的WordPress版本上。請忽略。

相關問題