You are here

Drupal 7 - Adding Vocabularies and Terms

In a couple of the Simple Content Type examples we have done so far there has been a required helper module which creates and adds a vocabulary with some terms using the Taxonomy module. Creating vocabularies and terms through code is a fairly straightforward process. We will use two hooks and several helper functions to handle all the lifting. First thing, let's define the hook_install() and hook_uninstall() functions:


/**
 * Implements hook_install().
 * - Create our vocabulary (ies)
 * - Add some terms
 */
function simple_vocab_install() {
  // create and add the andy_pangus taxonomy vocabulary and add some terms
  _create_vocabularies();
  _add_terms();
}
/**
 * Implements hook_uninstall().
 */
function simple_vocab_uninstall() {
  // delete the vocabularies and any taxonomy terms created
  _remove_vocabulary('andy_pangus');
}

The first thing we do is create any vocabularies we want to add and then we add some terms to the vocabularies we created. In the uninstall function we simply remove any vocabularies we created. Moving on to the meat of the module, let's take a look at the functions used to create, add, and remove vocabularies:


/**
 * Create any vocabularies needed for this content-type
 */
function _create_vocabularies() {
  _add_vocabulary(t('Andy Pangus'), 'andy_pangus', t('A list of terms to use along with the Simple Content Type dynamic checkboxes demo.'), 1);
}
/**
 * Add a vocabulary to the taxonomy tree
 *  @name - the human readable name for the vocabulary
 *  @machine_name - the machine name for the vocabulary
 *  @description - the human readable description for the vocabulary
 *  @weight - the weight for the vocabulary
 */
function _add_vocabulary($name, $machine_name, $description, $weight)  {
  $vocabulary = taxonomy_vocabulary_load(variable_get($machine_name . '_vocabulary', 0));
  if (!$vocabulary)  {
    $edit = array(
      'name' => $name,
      'machine_name' => $machine_name,
      'description' => $description,
      'hierarchy' => 1,
      'module' => 'simple_vocab',
      'weight' => $weight,
    );
    $vocabulary = (object) $edit;
    taxonomy_vocabulary_save($vocabulary);
    variable_set($machine_name . '_vocabulary', $vocabulary->vid);
  }  
}
/**
 * Remove the specified vocabulary
 *  $machine_name - the machine name for the vocabulary which is to be removed
 */
function _remove_vocabulary($machine_name)  {
  // delete the vocabularies and any taxonomy terms created
  $vid = db_select('taxonomy_vocabulary', 'v')
    ->fields('v', array('vid'))
    ->condition("v.machine_name", $machine_name)
    ->execute()
	->fetchField();
  taxonomy_vocabulary_delete($vid);
}

The first function we define is the _create_vocabularies() function. This function is a holder for the list of function calls which actually add the vocabulary to Drupal using the taxonomy module. The function we actually use to add the vocabulary takes four parameters: $name - the human readable name for the vocabulary which should have the first letter capitalized as you would for proper names, $machine_name - the machine name for the vocabulary which should be all lower case and use the underscore character instead of spaces, $description - the human readable description for the vocabulary, and $weight - the weight for the vocabulary which is used when determining the display order for multiple vocabularies. Following the API documentation we pass the value for any strings we define through the translation (t()) function when they are defined and never use t() to translate the variables themselves. The _add_vocabulary() function first tries to load a vocabulary using the machine name supplied and if we find that the vocabulary already exists we do not add it again. We then create an associative array of settings which is then typed as an object before being saved. Finally we define a function to remove a vocabulary based on it's machine name, which happens to be the only parameter we need for this function. Now that we have our vocabulary set up let's create and add some terms to it:


/**
 * Add terms to vocabularies
 */
function _add_terms() {
	// Client Names
	_create_term('andy_pangus', t('Drupal 5'), t('Legacy version'));
	_create_term('andy_pangus', t('Drupal 6'), t('Previous version'));
	_create_term('andy_pangus', t('Drupal 7'), t('Current version'));
	_create_term('andy_pangus', t('Drupal 8'), t('Coming soon'));
	_create_term('andy_pangus', t('WAMP'), t('Windows Apache, MySQL, and PHP'));
	_create_term('andy_pangus', t('LAMP'), t('Linux Apache, MySQL, and PHP'));
	_create_term('andy_pangus', t('MAMP'), t('Mac Apache, MySQL, and PHP'));
}
/**
 * Create a single term and add to a specific vocabulary if not already present
 *	@vocab - the machine name of the vocabulary
 *	@term - the human readable name of the term to be added
 *	@desc - the humna readable description of the term to be added (Optional)
 *      @weight - the weight of the term in the vocabulary list (Optional)
 */
function _create_term($vocab, $term, $desc = '', $weight = 0)  {
	$added = NULL;
	$added = taxonomy_get_term_by_name($term);
	if ($added == '' || $added == NULL)  {
		$vocabulary = taxonomy_vocabulary_machine_name_load($vocab);
		$vid = $vocabulary->vid;
		$new_term = array(
			'name' => $term, 
			'description' => $desc, 
			'parent' => array(0), 
			'weight' => $weight,
			'vid' => $vid,
		);
		$term_obj = (object) $new_term;
		taxonomy_term_save($term_obj);
	}
}

Just like we did for the vocabulary functions we use _add_terms() to make a set of calls to the function that actually does the work. That function, _create_term(), takes four parameters: $vocab - the machine name of the vocabulary which should be all lowercase letters with no spaces, $term - the human readable name of the term to be added, $desc - the human readable description of the term to be added (this parameter is optional), $weight - the weight of the term in the vocabulary list (this parameter is also optional). This function first checks to see that the term has not already been added to the vocabulary it is being assigned to before loading the vocabulary in question so we can use it's machine name to get the vid. We then create an associative array with term specific settings and then type it as an object before saving the term using the taxonomy module. That's the bulk of what we need for this module. We do still need to tell Drupal about our module and even though there is no actual code in it without the module.module file Drupal won't see it when we try to enable it:


/**
 * @file
 * This file is required for all modules
 */



And lastly here's the module.info file:


name = Simple Vocabulary
description = A vocabulary and terms to be used with the Simple Content Type demo
package = Andy Pangus Examples
core = 7.x
files[] = simple_vocab.install
files[] = simple_vocab.module

You should now be able to create and add your own vocabularies and terms for use with your modules.

Download the source for this example.

Tags: