1

I have a loop that outputs <option> fields for a <select> group. It contains many cities' names for many travel packs that I am publishing. The trick is that I need avoid repeated values.

For instance: I have 4 travel packs departing from Chicago, 5 from Orlando, 3 from Los Angeles e 2 from New York.

So, it outputs:
Select your city
Chicago
Chicago
Chicago
Chicago
Orlando
Orlando
Orlando
Orlando
Orlando
Los Angeles
Los Angeles
Los Angeles
New York
New York

I would need to print only one of them!

<select name="nDep" id="iDep" onchange="this.form.submit();">
<option selected disabled>Outras saídas disponíveis</option>
  <?php
    $args = array(
      'post_type'     => 'packs',
      'order'         => 'ASC'
    );
    $the_query = new WP_Query( $args );
    if(have_posts() ) : while ( $the_query->have_posts() ) : $the_query->the_post();
  ?>

<option value="<?php the_field('departures'); ?>"><?php the_field('departures'); ?></option>

  <?php endwhile; endif; ?>
</select>
3

I don't know of any WordPress-specific way to exclude duplicate-title posts from a query and I'm sure that there are multiple ways to address this. The solution that jumps to mind is to store each post title in an array and then check to see if that title is already there before outputting the post.

Some quick untested code:

<?php
    $args = array(
      'post_type'     => 'packs',
      'order'         => 'ASC',
      'orderby'       => 'title'
    );
    $the_query = new WP_Query( $args );
    // array to store cities
    $unique_cities = array();
    if( $the_query->have_posts() ) : while ( $the_query->have_posts() ) : $the_query->the_post();
        $city = get_the_field('departures');
        // only create option if city hasn't been added yet
        if( ! in_array( $city, $unique_cities ) ) :
            // add city to array so it doesn't repeat
            $unique_cities[] = $city;
    ?>

            <option value="<?php echo $city; ?>"><?php echo $city; ?></option>

  <?php
    endif;
  endwhile; endif; ?>

Also, note two other minor changes that I think you intended:

  • added orderby parameter to WP_Query so that cities are listed A-Z.
  • fixed first have_posts() so it's testing your custom query
|improve this answer|||||
  • Looks like the city is a custom field and not the post title. So if you need to add it the custom field to the array you should use get_field instead. – gdaniel Jul 17 '14 at 22:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.