Taxonomy Terms in Code
In a recent project, I was tasked with creating a number of taxonomies, each having a number of predefined terms provided by the client. Because we were working on the initial build of the site, we wanted to keep these taxonomies in code so we could install them easily.
The Features module will handle the exporting of vocabularies with ease, but Drupal considers terms to be content, so I had to come up with a separate solution to install the terms.
In my research, I discovered a variety of approaches I could take to get terms into code; use Drupal’s hook_install(), the UUID_Features module or the Default Content module.
To keep things as simple as possible, and without relying on other modules, I went with the hook_install() method.
This following is an example of my install hook from my project_xyz_taxonomy_terms.install file.
<?php
/**
* Implementation of hook_install().
*/
function project_xyz_taxonomy_terms_install(){
//Compass taxonomy terms
$compass = array(
'North',
'East',
'South',
'West',
);
_project_xyz_taxonomy_terms_load_terms($compass, 'compass');
//Seasons taxonomy terms
$seasons = array(
'Winter',
'Spring',
'Summer',
'Fall',
);
_project_xyz_taxonomy_terms_load_terms($seasons, 'seasons');
}
?>Also in the .install file, this function will perform the import of terms.
<?php
/**
* Custom function to load an array of terms into a specified vocabulary.
*/
function _project_xyz_taxonomy_terms_load_terms($terms, $vocab_name){
$vocab = taxonomy_vocabulary_machine_name_load($vocab_name);
if ($vocab == false) {
drupal_set_message('Error while attempting to install vocabulary ' . $vocab_name, 'error');
}
else {
foreach($terms as $weight => $term){
$data = new stdClass();
$data->name = $term;
$data->vid = $vocab->vid;
$data->weight = $weight;
taxonomy_term_save($data);
}
}
}
?>Assumptions:
-We’ve exported a feature with these two vocabularies.
-The vocabularies feature is weighted higher than the ‘project_xyz_taxonomy_terms’ module (to ensure the vocabularies exist before trying to load terms into them).



Comments
Export terms in "features extra"
A patch exists to do that in "features extra" http://drupal.org/node/755986. It woks well for us
Post new comment