Search code examples
phpwordpressarray-intersect

Multi-select add selected attribute if the value is present in the main array - php


I am working with a multi-select and GET method.I want multiple options selected when the form is reloaded after submitted based on the $_GET method from url parametres.i have associated URL parametres is cuisine%5B%5D=indian&cuisine%5B%5D=thai.Actually multi-select is about cuisine.

And my codes are below:

 <select name="cuisine[]" class="selectpicker show-tick form-control" data-selected-text-format="count > 3" data-done-button="true" data-done-button-text="OK" multiple>
    <?php
        $selected_cuisine = $_GET['cuisine'];
        // Get all cuisines list by get_terms() function.Its built in wordpress
        $restaurant_cuisines = get_terms('cuisine', array('hide_empty' => false));
        $cuisines = array();
        foreach ($restaurant_cuisines as $restaurant_cuisine) {
            // echo $restaurant_cuisine;
            array_push( $cuisines, $restaurant_cuisine->slug );
            // echo $cuisines_list;
        }
        print_r ($selected_cuisine);
        print_r($cuisines);
        if(array_intersect($selected_cuisine, $cuisines)){
            $selected = 'selected';
        }else{
            $selected = '';
        }
        foreach ($restaurant_cuisines as $cuisine) {
            echo '<option value="'. $cuisine->slug .'" '. $selected .' >'. $cuisine->name .'</option>';
        }
    ?>
</select>

But the problem is that every options is getting selected.Actually there is total 3 cuisines : indian, thai & chainese and 2 of them are selected -> indian and thai.But problem is 3 options are selected. :/


Solution

  • Remember when you are using array_intersect it is setting true is at least one match in both array.So everything is getting selected.Rather you can try this:

    <select name="cuisine[]" class="selectpicker show-tick form-control" data-selected-text-format="count > 3" data-done-button="true" data-done-button-text="OK" multiple>
    <?php
        $selected_cuisine = $_GET['cuisine'];
        // Get all cuisines list by get_terms() function.Its built in wordpress
        $restaurant_cuisines = get_terms('cuisine', array('hide_empty' => false));
        $cuisines = array();
        foreach ($restaurant_cuisines as $restaurant_cuisine) {
            array_push( $cuisines, $restaurant_cuisine->slug );
        }
        foreach ($restaurant_cuisines as $cuisine) {
            if(in_array($cuisine->slug, $selected_cuisine)){
              $selected = 'selected';
            }else{
              $selected = '';
            }
            echo '<option value="'. $cuisine->slug .'" '. $selected .' >'. $cuisine->name .'</option>';
        }
    ?>