使用此代码,所选选项将保存到数据库中:
<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 :(得分: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>
答案 1 :(得分:0)
这很令人尴尬。问题出在我的WordPress版本上。请忽略。