Drupal 7 – list taxonomy terms

I’m running some tests and thought I’d post the php code to display the terms for a taxonomy:

<?php
$terms = taxonomy_get_tree(taxonomy_vocabulary_machine_name_load('temp_auth_temp_agency')->vid);
if ($terms) {
  foreach ($terms as $term) {
    $options[$term->tid] = str_repeat('-', $term->depth) . $term->name;
  }
}
echo '<pre>$options: '. print_r($options,true) . '</pre>';

/* Returns:
$options: Array
(
    [439] => DePaul
    [441] => Express
    [440] => Galt Foundation
    [442] => Kelly Services
    [443] => Manpower
    [444] => Personnel Source
)
*/
?>

At the moment I’m considering leveraging the benefits of CCK Select Other for ease of entry with taxonomies for term management. Not sure if it’ll be worth it but this was an interesting code hunt.


Edit…

This one may be even more fun:

<?php
$terms = taxonomy_get_tree(taxonomy_vocabulary_machine_name_load('temp_auth_position_type')->vid);
if ($terms) {
  foreach ($terms as $term) {
    $options[preg_replace("/[()*+?.[]^${}|/!'#%&`",-:;<=>@~]/","",str_replace(" ","_",strtolower($term->name)))] = str_repeat('-', $term->depth) . $term->name;
  }
}
echo '<pre>$options: '. print_r($options,true) . '</pre>';

/* Returns:
$options: Array
(
    [catering] => Catering
    [clerical] => Clerical
    [custodial] => Custodial
    [food_service] => Food Service
    [laborer] => Laborer
    [programming] => Programming
)*/
?>
Comments
  • vid@uoregon.edu says:

    So I used the above in D7 inside a Term Reference with autocomplete_widgets installed. Ref: https://drupal.org/project/autocomplete_widgets

    In D6 the scenario is simiar; also with autocomplete_widgets installed but you use a text field and choose “Autocomplete for allowed values list” for the widget type.

    Here’s the code I used to pull in a taxonomy:

    $terms = taxonomy_get_tree(16); // UO Departments
    if ($terms) {
      foreach ($terms as $term) {
        $options[$term->tid] = str_repeat('-', $term->depth) . $term->name . ' ' . $term->description;
      }
    }
    return $options;
Leave a Comment