5

I'm attempting to create taxonomy terms in a module that provides the vocabulary needed to create these terms.

The issue I'm having is the vocabulary is not available upon install.

My module implements hook_taxonomy_default_vocabularies. I would like to create these terms in hook_install.

What is the best way to create these terms?

4

Although you can use hook_install(), it's best to use hook_enable() to check if the vocabulary exists and, if not, create it programatically:

$vocabularies = taxonomy_vocabulary_get_names();
$pos = array_search('my_vocabulary', $vocabularies);

if ($pos !== FALSE) {
  // its a keyed array so the $vid is actually $pos
  $vid = $pos;
} else {
  // arrays are more convenient to initialize
  $vocabulary = array(
     'name' => t('My Vocabulary'),
     'machine_name' => 'my_vocabulary',
     'description' => t('My description'),
     'hierarchy' => 1,
     'module' => 'your_module', // or nothing
     'weight' => 1
   );
   // argument must be an object
   $vocabulary = (object) $vocabulary;
   taxonomy_vocabulary_save($vocabulary);
   // horray, we have a vid now
   $vid = $vocabulary->vid;
}

// now that the vocab exists and you know the $vid, create your terms
// ...
  • 1
    I ended up removing features taxonomy export and just moving it to hook_install. Basically what you put here. Thanks for input. – troynt Apr 20 '11 at 0:15
  • 1
    how do you establish a relationship with a content type? – Aditya M P Apr 13 '12 at 6:04
  • oh sorry, I forgot this is done from the contenttype's end rather than the vocabulary's now in 7 – Aditya M P Apr 13 '12 at 6:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.