Skip to content

Instantly share code, notes, and snippets.

@zaclittleberry
Last active March 5, 2017 15:04
Show Gist options
  • Save zaclittleberry/dd929ab64ae22dc39a34bfd0edcbb320 to your computer and use it in GitHub Desktop.
Save zaclittleberry/dd929ab64ae22dc39a34bfd0edcbb320 to your computer and use it in GitHub Desktop.
Drupal hierarchical taxonomy terms find/create from an array
<?php
/**
* Helper function to retrieve tid of nested term, by tracing or creating terms.
*
* @param array $term_names
* The term names used to create the hierarchy from the parent to the child.
*
* @param string $vocabulary
* The machine name of the vocabulary the terms should be found/built within.
*
* @return
* The tid of the last term in the array.
*/
function taxonomy_find_create_nested_terms($term_names, $vocabulary) {
$terms_string = implode('|', $term_names);
$vocab_and_terms = hash('md5', $vocabulary . "_" . $terms_string);
if ($cache = cache_get('taxonomy_find_create_' . $vocab_and_terms)) {
$current_tid = $cache->data;
return $current_tid;
}
else {
$vocabularies = taxonomy_vocabulary_get_names();
$vid = $vocabularies[$vocabulary]->vid;
$current_tid = '0';
$create_term = FALSE; // We start with the assumption we will find terms
foreach ($term_names as $term_name) {
// If $create_term == True, we want to skip searching the DB
if (!$create_term) {
$record = taxonomy_find_term_by_name_and_parent($current_tid, $term_name, $vid);
if ($record) { // Term exists
$current_tid = $record['tid'];
}
else {
$create_term = TRUE; // Terms will need created from here on out
}
}
// This needs to be a separate conditional to catch $create_term when flipped
if ($create_term) {
// Term needs to be created
$term = new stdClass();
$term->name = $term_name;
$term->vid = $vid;
$term->parent = $current_tid;
taxonomy_term_save($term);
$current_tid = $term->tid;
}
}
cache_set('taxonomy_find_create_' . $vocab_and_terms, $current_tid);
return $current_tid;
}
}
/**
* Helper function to find a term by name in vid when it has a specific parent
*
* @param string $parent_tid
* The parent tid by which to filter terms
*
* @param string $term_name
* The term name for which to search
*
* @param string $vid
* The vocabulary id for which to filter terms
*
* @return
* The first record returned by the query.
*/
function taxonomy_find_term_by_name_and_parent($parent_tid, $term_name, $vid) {
$query = db_select('taxonomy_term_data', 'd');
$query->join('taxonomy_term_hierarchy', 'h', 'h.tid = d.tid');
$result = $query
->fields('d', array('tid', 'name', 'weight'))
->fields('h', array('parent'))
->orderBy('weight', 'ASC')
->condition('d.vid', $vid)
->condition('h.parent', $parent_tid)
->condition('d.name', $term_name)
->execute();
$record = $result->fetchAssoc();
return $record;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment