选择当前下拉值 - WordPress主题选项

时间:2014-01-16 04:38:25

标签: php wordpress drop-down-menu

不是仅选择当前值,而是选择它们。当我回显当前值时,它会正确显示,但我似乎无法弄清楚如何让它被选中。

<?php
echo $settings['featured-one'];
$cats = get_categories();
echo '<select name="sa_options[featured-one]"><option value="select">Select</option><option value="empty">Categories</option>';
foreach($cats as $cat){
    if ($cat->term_id.$cat->slug == $settings['featured-one']) $selected = 'selected="selected"';
    echo '<option value="'.$cat->term_id.$cat->slug.'" '.$selected.'> - '.$cat->name.'</option>';   
}
$pgs = get_pages();
echo '<option value="empty">Pages</option>';
foreach($pgs as $pg){
    if ($pg->ID.$pg->post_name == $settings['featured-one']) $selected = 'selected="selected"';
    echo '<option value="'.$pg->ID.$pg->post_name.'" '.$selected.'> - '.$pg->post_title.'</option>';
}
$posts = get_posts();
echo '<option value="empty">Posts</option>';
foreach($posts as $post){
    if ($post->ID.$post->post_name == $settings['featured-one']) $selected = 'selected="selected"';
    echo '<option value="'.$post->ID.$post->post_name.'" '.$selected.'> - '.$post->post_title.'</option>';
}
echo '</select>';
?>

2 个答案:

答案 0 :(得分:0)

尝试WordPress默认技术而不是我们自己的

参考链接selected function

<!-- Testing the values with if() -->
<select name="options[foo]">
    <option value="1" <?php if ( $options['foo'] == 1 ) echo 'selected="selected"'; ?>>1</option>
    <option value="2" <?php if ( $options['foo'] == 2 ) echo 'selected="selected"'; ?>>2</option>
    <option value="3" <?php if ( $options['foo'] == 3 ) echo 'selected="selected"'; ?>>3</option>
</select>

<!-- Using selected() instead -->
<select name="options[foo]">
    <option value="1" <?php selected( $options['foo'], 1 ); ?>>1</option>
    <option value="2" <?php selected( $options['foo'], 2 ); ?>>2</option>
    <option value="3" <?php selected( $options['foo'], 3 ); ?>>3</option>
</select>

答案 1 :(得分:0)

根据上述评论,我在每个if语句之前放置了$selected = '';