Support

Account

Home Forums Backend Issues (wp-admin) Populate Selects, but appearing duplicated

Solving

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

  • What kind of fields are they?

  • Hello John! thanks! I did it with your help. I was forgetting to close ifs.

Viewing 5 posts - 1 through 5 (of 5 total)

You must be logged in to reply to this topic.