How can I get the terms of a vocabulary using vocabulary machine name.

I have used the following code, although it works for me but I am looking for efficient methods.

$vocabulary = taxonomy_vocabulary_machine_name_load('school_courses');
$terms = taxonomy_get_tree($vocabulary->vid);
$courses = array();
foreach($terms as $term) {
    $courses[$term->tid] = $term->name;
}
up vote 5 down vote accepted

What you are doing is pretty much the same as Drupal core is doing for the term reference field, so doubt you can improve the code much.

/**
 * Returns the set of valid terms for a taxonomy field.
 *
 * @param $field
 *   The field definition.
 * @return
 *   The array of valid terms for this field, keyed by term id.
 */
function taxonomy_allowed_values($field) {
  $options = array();
  foreach ($field['settings']['allowed_values'] as $tree) {
    if ($vocabulary = taxonomy_vocabulary_machine_name_load($tree['vocabulary'])) {
      if ($terms = taxonomy_get_tree($vocabulary->vid, $tree['parent'])) {
        foreach ($terms as $term) {
          $options[$term->tid] = str_repeat('-', $term->depth) . $term->name;
        }
      }
    }
  }
  return $options;
}

Using EntityFieldQuery, you can add

->entityCondition('bundle', 'my_machine_name') to get terms by vocabulary name:

Example:

$query = new EntityFieldQuery();
$result = $query->entityCondition('entity_type', 'taxonomy_term')
                ->entityCondition('bundle', 'my_machine_name')
                ->execute();

I use EntityFieldQuery:

// Get vid from machine_name
$my_vocabulary = taxonomy_vocabulary_machine_name_load('my_machine_name');
$my_vid = $my_vocabulary->vid;

// Build and execute the query 
$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'taxonomy_term')
    ->propertyCondition('vid', $my_vid)
$result = $query->execute();

// Process the result
var_dump($result);

Output:

array(1) {
  ["taxonomy_term"]=>
  array(8) {
    [12]=>
    object(stdClass)#145 (1) {
      ["tid"]=>
      string(2) "12"
    }
    [14]=>
    object(stdClass)#149 (1) {
      ["tid"]=>
      string(2) "14"
    }
    /* etc... */
  }
}

http://api.drupal.org/api/drupal/includes!entity.inc/class/EntityFieldQuery/7

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

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