2017-12-28 37 views
0

私はフォームフィールドの選択に基づいて、カスタムフィールドなどのために投稿を検索する検索フォームを持つワードプレスサイトを持っています。それはうまくいきますが、検索結果ページでは、私は検索クエリ/ URL文字列に基づいてフォームの選択をプリセットしようとしています。複数のドロップダウンリストとブートストラップを含むセット

私は定期的なselectドロップダウンを使用しており、チェックボックスを使用してマルチセレクションのブートストラップを使用できるように "multiple"に設定しています。私は同様の質問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

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>

関連する問題