Drupal 7 – Create a taxonomy term selection list of a specific vocabulary @ 1

Next: Drupal 7 – Create a taxonomy term selection list of a specific vocabulary @ 2

I want to create a HTML selection list which contains the taxonomy terms of a vocabulary. When a option is selected, the browser will go to the selected term page. In this post, i would like to share how to generate a selection list by PHP.

I have a vocabulary which has terms in 2-level. The selection list could generated as follow.

<select id="my-selection-list">
  <option value="0"><?php print t('Select a term'); ?></option>
  <?php
    $vid = <vocabulary-id>;
    $terms = taxonomy_get_tree($vid);
    foreach($terms as $term) {    
      if ($term->parents[0] == 0) {
        print '<option value="' . $term->tid . '">' . $term->name . '</option>';
      } else {
        print '<option value="' . $term->tid . '"> - ' . $term->name . '</option>';
      }
    }
  ?>
</select>

 

If you have deeper term level, you need to edit the $term->parent checking such that it could render the terms in proper hierarchy level.

Done =)

Reference: Drupal API – taxonomy_get_tree

Advertisements

One thought on “Drupal 7 – Create a taxonomy term selection list of a specific vocabulary @ 1”

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s