Isset with multi select dropdown and bootstrap

admin

Administrator
Staff member
I have a wordpress site with a search form that searches for posts based on the form field selections, for custom fields etc. It works fine, however on the search results page I have an exact copy of the form except that I am trying to preset the form selections based on the search query/url string.

I am using a regular select dropdown and I have set it to "multiple" so that it can use bootstraps multiselect with the checkboxes. I've asked a similar question <a href="https://stackoverflow.com/questions/47557998/using-isset-with-checkboxes">HERE</a> but that was for checkboxes and even though the bootstrap multiselect uses checkboxes, I still have to work with the select dropdown first.

So after trying several things, I've come close but have ran into several problems. In the code below I made notes to further explain exactly what I mean.

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

if ( $count &gt; 0  ){
        echo "&lt;option value='Any'&gt;All&lt;/option&gt;";

        foreach ( $terms as $term ) {

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

// FIRST EXAMPLE
$selected .= ($proptypes === $term-&gt;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-&gt;slug) ? "selected" : "";   // shows only last correct selected value
//if ($proptypes === $term-&gt;slug) { $selected = 'selected'; }   // shows first correct selected value then selects every value after, even if it wasn't selected

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


    } 
}
      echo "&lt;option value='" . $term-&gt;slug . "' " . $selected . "&gt;" . $term-&gt;name . "&lt;/option&gt;";                  // FIRST EXAMPLE

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

    }
}
?&gt;
&lt;/select&gt;