Hello there,
I have a little issue and need your help.
I’m trying to create a dropdown menu from all the values of a custom field. For example I have a custom post type ‘locations’ with custom field ‘country’. I want to take all the countries and put them into a <select>.
I succeeded to get all countries but if I have one country used in more that one location it shows twice or more. How can I distinct the results? I managed to do it with jQuery but I don’t think it’s the right way.
Here is the code that I use to get the fields:
$args = array(
'post_type' => 'locations',
'posts_per_page' => -1,
'meta_query' => array(
array(
'key' => 'country',
)
),
);
$query = new WP_Query( $args );
if($query->have_posts()) :
echo "<select name='country' class='form-control' id='countryselect'>";
while($query->have_posts()) :
$query->the_post();
echo "<option>" . get_field('country') . "</option>";
endwhile;
echo "</select>";
endif;
Thanks in advance!
Hi @v0rt3x
You can add some simple logic to test if the option has already been added like so:
<?php
$added = array();
$args = array(
'post_type' => 'locations',
'posts_per_page' => -1,
'meta_query' => array(
array(
'key' => 'country',
)
),
);
$query = new WP_Query( $args );
if($query->have_posts()) :
echo "<select name='country' class='form-control' id='countryselect'>";
while($query->have_posts()) :
$query->the_post();
// get country
$country = get_field('country');
// bail early if this country has already been added
if( in_array($country, $added) )
{
continue;
}
// add country
$added[] = $country
echo "<option>" . $country . "</option>";
endwhile;
echo "</select>";
endif;
?>
Hope that helps.
Thanks
E
Thank you @elliot for the help, it worked perfectly 🙂