简体   繁体   中英

How do you list down child taxonomies and parent taxonomies with no children using get_terms?

I'm currently working on a website that lists down names of locations using Taxonomies and the get_terms function for a drop-down list form. The list goes as follows:

Batangas
Cagayan De Oro
Metro Manila
— Manila
— Muntinlupa
— Quezon City
— San Juan City
Naga and Dagupan
— Dagupan City
— Naga City
Provincial Areas
— Cavite
— Davao
— General Santos City
— Los Baños, Laguna
— Lucena City
— San Pablo City, Laguna
— San Pedro, Laguna
— Sta. Rosa, Laguna
Taguig

However, I'm looking for a way to omit the terms in bold because these terms are parent terms that are only meant to be used by another post type for another part of the website to group these terms, in order to reflect my client's location-based pricing schemes.

PHP:

<?php $taxonomy = 'location'; $terms = get_terms( $taxonomy);
if ( $terms && !is_wp_error( $terms ) ) : ?>

<select name='location'>
    <option selected disabled>Choose a location</option>
    <?php foreach ( $terms as $term ) { ?>
    <?php if ($term->parent != 0) : ?>
        <option value='<?php echo $term->slug; ?>'><?php echo $term->name; ?></option>
    <?php endif; ?>
    <?php } ?>
</select>

Using this query you can find only parent taxonomies.

$args = get_terms( array( 
  'taxonomy' => 'taxonomy_name',
  'orderby' => 'name',
  'order' => 'ASC',
  'hide_empty' => 0,
  'parent' => 0
));
if ( !empty($taxonomies) ) :
   foreach( $taxonomies as $category ) {
       echo $category->name;
   }
endif;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM