Skip to content

Instantly share code, notes, and snippets.

@massiws
Last active October 12, 2016 23:57
Show Gist options
  • Save massiws/36ebf92e3e4bcb135516 to your computer and use it in GitHub Desktop.
Save massiws/36ebf92e3e4bcb135516 to your computer and use it in GitHub Desktop.
Create custom vocabulary and terms in Drupal 7
<?php
/**
* Implements hook_install().
*/
function my_module_install() {
// Create a new vocabulary, if don't exists
$vmn = 'my_vocabulary'; // Vocabulary Machine Name
$voc = taxonomy_vocabulary_machine_name_load($vmn);
if (!$voc) {
$vid = _createNewVocabulary('My vocabulary', $vmn, 'Vocabulary description', 'my_module');
// Create terms for the vocabulary
_createNewTaxonomyTerm('My term 1', $vid, $vmn, 'Term 1 description');
_createNewTaxonomyTerm('My term 2', $vid, $vmn, 'Term 2 description');
_createNewTaxonomyTerm('My term 3', $vid, $vmn, 'Term 3 description');
}
}
/**
* Create a new taxonomy vocabulary.
*
* @param string $name Vocabulary uman-readable name
* @param string $vmn Vocabulary machine name
* @param string $description Description of vocabulary
* @param string $module Name of the calling module
* @return integer Vocabulary ID
*/
function _createNewVocabulary($name, $vmn, $description, $module) {
$vocabulary = new stdClass();
$vocabulary->name = $name;
$vocabulary->machine_name = $vmn;
$vocabulary->description = $description;
$vocabulary->module = $module;
taxonomy_vocabulary_save($vocabulary);
return $vocabulary->vid;
}
/**
* Create a new taxonomy term.
*
* @param string $name Name of taxonomy term
* @param integer $vid Vocabulary ID
* @param string $vmn Vocabulary machine name
* @param string $description Description of the term
* @return integer Term ID
*/
function _createNewTaxonomyTerm($name, $vid, $vmn, $description) {
$term = new stdClass();
$term->name = $name;
$term->vid = $vid;
$term->vocabulary_machine_name = $vmn;
$term->description = $description;
taxonomy_term_save($term);
return $term->tid;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment