[Drupal] How to create a Drupal taxonomy vocabulary programmatically

| | 1 min read

I have created a module for my Drupal project. That module requires a vocabulary that should be created when installing the module itself. To create the vocabularies, while installation itself we have to implement the code in the install hook. Read on to know the code to create a vocabulary named as 'Categories'.

  
    /**
     * Implements hook_install().
     * Creates the vocabulary programmatically and set a variable to store the 
     * vocabulary id in the variable table
     */
    function mymodule_install() {
      $vocabulary = taxonomy_vocabulary_load(variable_get('categories', 0));
      if (!$vocabulary) {
        $edit = array(
          'name' => t('Categories'),
          'machine_name' => 'categories',
          'description' => t('Image Categories'),
          'hierarchy' => 1,
          'module' => 'modulename',
          'weight' => -10,
        );
        $vocabulary = (object) $edit;
        taxonomy_vocabulary_save($vocabulary);
        variable_set('categories', $vocabulary->vid);
      }
    }
  

The above code will create a vocabulary 'Categories' with machine name as 'categories' and then stores its vocabulary id in a variable called 'categories' when installing the module itself.