Isset with multi select dropdown and bootstrap

时间:2017-12-28 17:50:45

标签: php wordpress twitter-bootstrap get isset

我有一个带有搜索表单的wordpress网站,根据表单字段选择,自定义字段等搜索帖子。它工作正常,但是在搜索结果页面上我有一个表单的确切副本,除了我是尝试根据搜索查询/网址字符串预设表单选择。

我正在使用常规选择下拉列表并将其设置为“多个”,以便它可以使用带有复选框的bootstraps multiselect。我问了一个类似的问题HERE,但那是复选框,即使引导程序多选使用复选框,我仍然必须先使用选择下拉列表。

所以在尝试了几件事后,我已经接近但遇到了几个问题。在下面的代码中,我做了笔记,以进一步解释我的意思。

<select name="property_type[]" id="pt-multi" class="form-control multi-select2" multiple="multiple">
<?php
$terms = get_terms( "property-type", array( 'hide_empty' => 0 ) );
$count = count($terms);

if ( $count > 0  ){
        echo "<option value='Any'>All</option>";

        foreach ( $terms as $term ) {

if (isset($_GET['property_type'])) {
        foreach ($_GET['property_type'] as $proptypes) {

// FIRST EXAMPLE
$selected .= ($proptypes === $term->slug) ? "selected" : "";  // shows first correct selected value but also selects everything after it up until the second correct value, which it doesn't select.
//$selected = ($proptypes === $term->slug) ? "selected" : "";   // shows only last correct selected value
//if ($proptypes === $term->slug) { $selected = 'selected'; }   // shows first correct selected value then selects every value after, even if it wasn't selected

// SECOND EXAMPLE
//$selected .= ($proptypes === $term->slug) ? "selected" : "";  // shows first correct selected value then selects every value after, even if it wasn't selected
//$selected = ($proptypes === $term->slug) ? "selected" : "";   // shows only last correct selected value
//if ($proptypes === $term->slug) { $selected = 'selected'; }   // shows first correct selected value then selects every value after, even if it wasn't selected


    } 
}
      echo "<option value='" . $term->slug . "' " . $selected . ">" . $term->name . "</option>";                  // FIRST EXAMPLE

      //echo "<option value='" . $term->slug . "' " . ($selected?' selected':'') . ">" . $term->name . "</option>"; // SECOND EXMAPLE 

    }
}
?>
</select>

1 个答案:

答案 0 :(得分:1)

创建并编译并使用in_array()进行检查。

<select name="property_type[]" id="pt-multi" class="form-control multi-select2" multiple="multiple">
<?php
$terms = get_terms("property-type", array('hide_empty' => 0));
$count = count($terms);

// Setup an array of $proptypes
$proptypes = array();
if (isset($_GET['property_type'])) {
    foreach ($_GET['property_type'] as $proptype) {
        $proptypes[] = $proptype;
    }
}

if ($count > 0) {
    echo "<option value='Any'>All</option>";
    foreach ($terms as $term) {
        $selected = (in_array($term->slug, $proptypes)) ? 'selected' : '';
        echo "<option value='" . $term->slug . "' " . $selected . ">" . $term->name . "</option>";
    }
}

?>
</select>