Skip to content

Instantly share code, notes, and snippets.

@batigolix
Created March 17, 2016 08:45
Show Gist options
  • Save batigolix/8a7bceb61fe9a10298d3 to your computer and use it in GitHub Desktop.
Save batigolix/8a7bceb61fe9a10298d3 to your computer and use it in GitHub Desktop.
Create vocabularies and terms
/**
* Create vocabulary and terms for Topic.
*/
function _g2m_initiative_create_taxonomies() {
// Defines taxonomies to be created.
$taxonomies = array(
'g2m_topics' => array(
'name' => t('Topics'),
'terms' => array(),
),
'g2m_subtopics' => array(
'name' => t('Sub topics'),
'terms' => array(),
),
'g2m_support_type' => array(
'name' => t('Support type'),
'terms' => array(),
),
'g2m_security' => array(
'name' => t('Security'),
'terms' => array(),
),
);
// Cycles through taxonomies to create vocabularies.
foreach ($taxonomies as $machine_name => $taxonomy) {
$vocabulary = taxonomy_vocabulary_machine_name_load($machine_name);
if (isset($vocabulary->vid)) {
watchdog('g2m_initiative', 'The vocabulary @name already exists, so it will not be created', array('@name' => $machine_name), WATCHDOG_INFO);
}
// Creates the vocabulary.
else {
taxonomy_vocabulary_save((object) array(
'name' => $taxonomy['name'],
'machine_name' => $machine_name,
));
// Loads the created vocabulary.
$vocabulary = taxonomy_vocabulary_machine_name_load($machine_name);
}
// Creates terms if they do not exist already.
foreach ($taxonomy['terms'] as $term_name) {
$existing_term = taxonomy_get_term_by_name($term_name, $vocabulary->machine_name);
if (count($existing_term) > 0) {
watchdog('g2m_initiative', 'The term @term_name already exists, so it will not be created', array('@term_name' => $term_name), WATCHDOG_INFO);
}
else {
$term = (object) array(
'vid' => $vocabulary->vid,
'name' => $term_name,
'description' => $term_name,
);
taxonomy_term_save($term);
watchdog('g2m_initiative', 'The term @term_name was created', array('@term_name' => $term_name), WATCHDOG_INFO);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment