Drupal load vocabulary from machine name

By default, you can only get vocabulary information if you have the vid. But what if you only have the machine_name? Here's a couple of handy functions that help:
<?php
/**
 * Gets a vocabulary entity from a vocabulary machine name
 * @return stdClass
 *  A vocabulary entity or FALSE if vocabulary doesn't exist
 */
function mymodule_taxonomy_get_vocab_by_machine_name($machine_name) {
  $vocab = FALSE;
  $results = db_select('taxonomy_vocabulary')
      ->fields('taxonomy_vocabulary')
      ->condition('machine_name', $machine_name)
      ->execute()
      ->fetchAll();
  if ($results) {
    $vocab = current($results);
  }
  return $vocab;
}
 
/**
 * Gets a vocabulary tree (array of term entities) from a vocabulary machine name
 * @return array Vocabulary terms
 */
function mymodule_taxonomy_get_tree_by_machine_name($machine_name) {
  $terms = array();
  $vocab = mymodule_taxonomy_get_vocab_by_machine_name($machine_name);
  if ($vocab) {
    $vid = $vocab->vid;
    $terms = taxonomy_get_tree($vid);
  }
  return $terms;
}
?>

Article Type

General