[Drupal] How to create a taxonomy vocabulary inside a custom module when enabled?

By | 10th Feb 2015 | 2 min read

I faced a problem to create a taxonomy vocabulary term when my custom module was enabled. To save a vocabulary we just need a Taxonomy vocabulary save. But here I had to enable it whenever my module is enabled. So I checked out and found this method to add a new taxanomy vocabulary.

Drupal 7 provides a function called hook_enable. This function performs necessary action once the module is enabled. I have used this functionality to add a new taxonomy vocabluary.

In my case I want to add a new Taxonomy vocabulary called Categories. The following code will explain you the process which I did.



    /**
     * Implements hook_enable().
     */

    function photoshare_enable() {
      $vocabulary = taxonomy_vocabulary_load(variable_get('photoshare_categories_vocabulary', 0));
      if (!$vocabulary) {
        $category = array(
          'name' => t('Categories'),
          'machine_name' => 'photoshare_categories',
          'description' => t('Photoshare categories vocabulary'),
          'hierarchy' => 1,
          'module' => 'photoshare',
        );
        $vocabulary = (object) $category;
        taxonomy_vocabulary_save($vocabulary);
        variable_set('photoshare_categories_vocabulary', $vocabulary->vid);
      }
    }

In the above code I checked whether the vocabulary is existing or not at first. If it is not existing then I added the vocabulary category with the required values as an array. Since the taxonomy_vocabulary_save() function needs its input as an object I converted it as an object and saved it. And I have set the value as well.

You can keep the vocabulary if you want even after the module is disabled in this method. If you dont want the vocabulary then you can use hook_disable and taxonomy_vocabulary_delete to delete it.