Creating vocabularies and taxonomy terms programmatically in Drupal 7

By Joel Stein on May 3, 2011

Here’s a little tip to create a vocabulary programmatically in Drupal 7.

taxonomy_vocabulary_save((object) array(
  'name' => 'Vocabulary Name',
  'machine_name' => 'vocab_short_name',
));

And, just in case you need to create a taxonomy term in your new vocabulary, you can do it with taxonomy_term_save. But first, we need to get the ID of the vocabulary we just created.

$vid = db_query("SELECT vid FROM {taxonomy_vocabulary} WHERE machine_name = 'vocab_short_name'")->fetchField();

Now, you can save your term with taxonomy_term_save.

taxonomy_term_save((object) array(
  'name' => 'Term name',
  'vid' => $vid,
));

What I was actually trying to do was create a hierarchical vocabulary of terms. In my scenario, I wanted to have a list of parent terms and corresponding children terms. Here’s what I did to accomplish this:

// Create the vocabulary.
taxonomy_vocabulary_save((object) array(
  'name' => 'Event Type',
  'machine_name' => 'event_type',
));

// Get the vocabulary ID.
$vid = db_query("SELECT vid FROM {taxonomy_vocabulary} WHERE machine_name = 'event_type'")->fetchField();

// Define the terms.
$terms['Group 1'][] = 'Some term 1';
$terms['Group 1'][] = 'Some term 2';
$terms['Group 1'][] = 'Some term 3';
$terms['Group 2'][] = 'Another term 1';
$terms['Group 2'][] = 'Another term 2';

foreach ($terms as $parent => $children) {
  // Create the parent term.
  taxonomy_term_save((object) array(
    'name' => $parent,
    'vid' => $vid,
  ));

  // Get the parent term's ID.
  $tid = db_query("SELECT tid FROM {taxonomy_term_data} WHERE vid = :vid ORDER BY tid DESC LIMIT 1", array(
    ':vid' => $vid,
  ))->fetchField();

  foreach ($children as $term) {
    // Create the child term.
    taxonomy_term_save((object) array(
      'name' => $term,
      'vid' => $vid,
      'parent' => array($tid),
    ));
  }
}