List Custom Terms in Options List

Today I’m trying to create a custom form through which users will able to search the site – specifically the products. In order to do so, I need to compile the terms of a given parameter, and list each on in a surrounding “option tag.”

So the first step is to get the terms. I’ll do this by using WordrPress’ “get_terms” function:

$type_terms = get_terms('type', array('hide_empty' => true));

The next step is to do a search of the posts for each of these terms.

  foreach($type_terms as $type_term) {
    $types = new WP_Query(array('orderby'=>'name', 'order' => 'ASC', 'hide_empty'=>true, 'post_type' => 
    'products', 'type' => $type_term->name));
  }

Once that’s set up, I want to iterate through every post found:

    while($types->have_posts()): $types->the_post();
      
    endwhile;

And in that while loop, I want make sure I only list each type once. So essentially, I need to create a way to check if that term we’re on has already been listed. If it has, we need to skip it. If it hasn’t been listed, then I want to list it. In order to do this, I’m going to create an array with all the terms we listed. With each new possible addition to the array, I want to check that it’s not already in there. If it, I’ll skip. If not, I’ll list it.

So above my “foreach” loop, I’ll add:

$types_array = array();
$i = 0;

Then I’ll go back to my while look and add the final check:

      if(!in_array($type_term->name, $types_array)) {
        $types_array[$i] = $type_term->name;
        echo '';		
      }
      $i++;

So, all in all, it looks like this:

$types_array = array();
$i = 0;
$type_terms = get_terms('type', array('hide_empty' => true));
  foreach($type_terms as $type_term) {
    $types = new WP_Query(array('orderby'=>'name', 'order' => 'ASC', 'hide_empty'=>true, 'post_type' => 
    'products', 'type' => $type_term->name));
    while($types->have_posts()): $types->the_post();
      if(!in_array($type_term->name, $types_array)) {
        $types_array[$i] = $type_term->name;
        echo '';		
      }
      $i++;
    endwhile;
  }
cw-index-1-r2
goUSF-index-1
usfgm-index-1-r3
bgl-index-1
ucon-index-1-r1
adopt-index-2
skalet-index-1-r2
pcabral
th-index-1
rms-index-2
km-index-1-r1
peu-index-2-r3b
pdu-index-1-r2a
oph-index-1-r2
mmm-index-1
long-index-1-r1a
ernies-index-1
cooks-index-1-r2a
df-index-1-r1
vs-index-1
uni-index-1
pe-wedding-print
Screen shot 2013-10-25 at 3.38.39 PM
fred
cabral
dava
psa
errg
apex
pag
cwb
beginners
awakealive
ecom
ab