Programmatically adding terms into a vocabulary from a structured text file
/**
* Implements hook_install().
*/
function artist_install() {
artist_install_vocabularies();
artist_install_terms();
}
/**
* Installs artist module's default terms that are read from
* text files in the module's includes folder.
*/
function artist_install_terms() {
foreach (array_keys(artist_vocabularies()) as $machine_name) {
$v = taxonomy_vocabulary_machine_name_load($machine_name);
$wrapper = entity_metadata_wrapper('taxonomy_vocabulary', $v);
if ($wrapper->term_count->value() == 0) {
$path = drupal_get_path('module', 'artist') . '/includes/terms_' . $v->machine_name . '.txt';
$lines = file($path, FILE_SKIP_EMPTY_LINES);
artist_install_term_tree($wrapper, $lines);
}
}
}
/**
* Installs a term tree.
* @param $vwrapper
* EntityMetadataWrapper of a taxonomy_vocabulary entity.
* @param $lines
* Array of lines from the term text file. The iterator must be set
* to the line to parse.
* @param $last
* Either NULL or the parent term ID.
* @param $depth
* Current depth of the tree.
*/
function artist_install_term_tree($vwrapper, &$lines, $last = NULL, $depth = 0) {
$wrapper = NULL;
while ($line = current($lines)) {
$name = trim($line);
$line_depth = max(strlen($line) - strlen($name) - 1, 0);
if ($line_depth $depth) {
$tid = $wrapper ? $wrapper->tid->value() : NULL;
artist_install_term_tree($vwrapper, $lines, $tid, $depth+1);
}
else {
$data = array(
'name' => $name,
'vid' => $vwrapper->vid->value(),
'parent' => array($last ? $last : 0),
);
$term = entity_create('taxonomy_term', $data);
$wrapper = entity_metadata_wrapper('taxonomy_term', $term); $wrapper->save();
next($lines);
}
}
}
/**
* Installs terms into default vocabularies.
*/
function artist_update_7201(&$sandbox) {
artist_install_terms();
}
In the preceding code, term names are read from text files that have tab indentation to symbolize the term hierarchy
Tags: