I created a list of countries using the ACF Wordpress plugin. The plugin allows for creation custom post meta fields so each post got an additional meta data namely the country name.
I get the country list with a WP_Query and store it in the
$result
$myquery = new WP_Query($myargs);
if ($myquery -> have_posts()) :
while ($myquery -> have_posts()) :
$myquery -> the_post();
array_push($arr, get_field('country'));
endwhile;
endif;
wp_reset_postdata();
$result = array_unique($arr);
<select name="countries" id="countries" class="form-control">
<?php
for ($i = 0; $i < count($result); $i++) :
$selected = (isset($_POST['countries']) && $result[$i] == $_POST['countries']) ? 'selected' : '';
$selected = ($result[$i] == @$_POST['countries']) ? 'selected' : '';
echo '<option value="' . $result[$i] . '" ' . $selected . '>' . $result[$i] . '</option>';
endfor;
?>
</select>
<?php
$selected = (isset($_GET['country']) && $result[$i] == $_GET['country']) ? 'selected="selected"': '';
?>
<option value="all">all</option>
$_POST
<form>…</form>
array_unique($arr)
does not reindex the keys of the array, so the for ($i = 0; $i < count($result); $i++)
loop does not work. You can either
$result = array_values(array_unique($arr));
or
foreach ($result as $country) {
$selected = (isset($_GET['countries']) && $country == $_GET['countries']) ? ' selected' : '';
echo '<option value="' . $country . '"' . $selected . '>' . $country . '</option>', "\n";
}
Working code: http://phpfiddle.org/main/code/fuy5-6f3c