2

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;
}

3 Answers 3

5

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;
}
3

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();
1

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 agree to our terms of service and acknowledge you have read our privacy policy.

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