Programmatically Creating a Vocabulary in Drupal 7

If you want your module to create a custom vocabulary, implement hook_install() and hook_uninstall() in your mymodule.install file. The vocabularies will be created and deleted on install/uninstall of the module.

Implement hook_install() and hook_uninstall()

/** 
 * Implements hook_install().
 */
function mymodule_install() {	
	// Create vocabularies.	
	foreach(_mymodule_get_vocabularies() as $vocabulary) {		
		// Convert to object.
		$vocabulary = (object) $vocabulary;		
		// Save the vocabulary.		
		taxonomy_vocabulary_save($vocabulary);		
		// Store the vid so we can delete the vocabulary later.		
		// Storing the vid is also useful for when we want to programmatically insert terms.		
		variable_set($vocabulary->machine_name . '_vid', $vocabulary->vid);	
	}
}

/** 
 * Implements hook_uninstall(). 
 */
function mymodule_uninstall() {	
	// Delete vocabularies.
	foreach(_mymodule_get_vocabularies() as $vocabulary) {
		// Convert to object.
		$vocabulary = (object) $vocabulary;		
		// Get the stored vid.		
		$vid = variable_get($vocabulary->machine_name . '_vid');		
		// Delete from database.		
		taxonomy_vocabulary_delete($vid);		
		// Delete the variable.		
		variable_del($vocabulary->machine_name . '_vid');
	}
}

/** 
 * Gets the list of vocabularies defined. 
 * @return 
 */
function _mymodule_get_vocabularies() {	
	return array(		
		array(			
			'name' => t('My New Vocabulary'),			
			'machine_name' => 'my_new_vocabulary'		
		),	
	);
}

Add a Term to a Vocabulary

Now that you have your vocabulary defined, here’s how to programmatically add terms to a vocabulary.

2 thoughts on “Programmatically Creating a Vocabulary in Drupal 7

  1. Eric Mulder Reply

    Nice article, thank you for sharing.

    taxonomy_vocabulary_delete() needs a vocabulary id (vid) as parameter. I think you forgot this in your code example. Issue is found on line #28.

Leave a Reply to Mirza Busatlic Cancel reply

Your email address will not be published. Required fields are marked *