Home › Forums › Backend Issues (wp-admin) › Populate Selects, but appearing duplicated
Hello Devs! how are you? I am populating a select, but the categories are appearing duplicated. I need help. And since I’m an initiator I would like to know if I’m doing it right. Thanks.
The code:
echo '<div class="input-field col m2 s12">';
echo '<select class="browser-default">';
query_posts('post_type=book');
if(have_posts()):
while (have_posts()) : the_post();
$terms = get_field('tipo_de_imovel');
if($terms):
foreach($terms as $term):
echo '<option value="'.esc_html($term->name).'">'.esc_html($term->name).'</option>';
endforeach;
endif;
endwhile;
endif;
echo '</select>';
echo '</div>';
The problem is that you are looping over posts and then looping over the terms attached to each post so multiple posts may have the same terms.
Question, do you really need to loop over the posts? Are you trying to only show terms that have been selected in posts?
Assuming that the answer to those questions is yes then you need to keep track of terms you’ve already shown and not show them again
if(have_posts()) {
$shown_terms = array();
while (have_posts()) {
the_post();
$terms = get_field('tipo_de_imovel');
if ($terms) {
foreach ($terms as $term) {
if (!in_array($term->name, $shown_terms)) {
$shown_terms[] = $term->name;
echo '<option value="'.esc_html($term->name).'">'.esc_html($term->name).'</option>';
} // end if not shown
} // end foreach $term
} // end if $terms
} // end while have_posts()
} // end if have_posts()
I want to do advanced search. I have 3 custom fields and need to insert their respective fields dynamically. I don’t know if I’m doing this correctly. This is my doubt.
District
– dist 1
– dist 2
– dist 3
Type
– type 1
– type 2
– type 3
Status
– status 1
– status 2
– status 3
Hello John! thanks! I did it with your help. I was forgetting to close ifs.
The topic ‘Populate Selects, but appearing duplicated’ is closed to new replies.
Welcome to the Advanced Custom Fields community forum.
Browse through ideas, snippets of code, questions and answers between fellow ACF users
Helping others is a great way to earn karma, gain badges and help ACF development!
We use cookies to offer you a better browsing experience, analyze site traffic and personalize content. Read about how we use cookies and how you can control them in our Privacy Policy. If you continue to use this site, you consent to our use of cookies.