Get terms of taxonomy by vocabulary name

Public

In this example this helper is used to create select field with taxonomy terms in form.
More informations on http://stackoverflow.com/a/10191370/568838

Get raw version
php
  1. /**
  2.  * helper function to get taxonomy term options for select widget
  3.  * @arguments string $machine_name: taxonomy machine name
  4.  * @return array of select options for form
  5.  */
  6. function MYMODULE_get_taxonomy_term_options($machine_name){
  7. $options = array();
  8.  
  9. $vid = taxonomy_vocabulary_machine_name_load($machine_name)->vid;
  10.  
  11. $options_source = taxonomy_get_tree($vid);
  12.  
  13. foreach($options_source as $item ) {
  14. $key = $item->tid;
  15. $value = $item->name;
  16. $options[$key] = $value;
  17. }
  18.  
  19. return $options;
  20. }
  21.  
  22. /**
  23. * Implements hook_form()
  24. */
  25. $form['field_name'] = array(
  26. '#options' => MYMODULE_get_tax_term_options('taxonomy_machine_name'),
  27. );

Comments

Nick's picture

Can I add that this will get the vocabulary loaded by machine name and not by the actual name that you see it listed on the vocabularies page.

To load it by name and not machine name:

  1. $vocabulary = taxonomy_vocabulary_load_multiple(NULL, array('name' => $real_name));
  2. $vid = reset($vocabulary)->vid;