[Drupal] How to get vocabulary id from vocabulary name in Drupal 6

| | 1 min read

I have a vocabulary in my drupal project and I want to make the vocabulary as a single select in one of my content types. I can do it in the form_alter. But to select the vocabulary item in the form_alter, I need its vocabulary-id. I dont want to hard code vocabulary-id in my code, so I searched for a drupal core function to get the vocabulary id from its name. In drupal 7 there is a function to get the entire vocabulary object from its machine name. But in drupal 6 there is no core function to get vocabulary id from its name. So I created a custom function to get the vocabulary id from its name. See the following function I programmed, to get the vocabulary id from its name.

  
    /**
     * To get the vocabulary id of a vocabulary from name.
     */
    function my_module_get_vocabulary_id_by_name($vocabulary_name) {
      $result = db_query("SELECT vid FROM {vocabulary} WHERE name = '%s'", $vocabulary_name);
      $vid = db_fetch_object($result)->vid;
      if($vid) {
        return $vid;
      }
      else {
        return FALSE;
      }
    }
  

The above custom function will be useful for you to get the vocabulary id from its name. It will return the vocabulary id if any vocabulary with that name exists in the system. Otherwise it will return FALSE.