Skip to content

Instantly share code, notes, and snippets.

@chupzzz
Created August 6, 2017 12:19
Show Gist options
  • Save chupzzz/f9dedc64ef9f60ea9d5d47116e1e6e05 to your computer and use it in GitHub Desktop.
Save chupzzz/f9dedc64ef9f60ea9d5d47116e1e6e05 to your computer and use it in GitHub Desktop.
Find taxonomy term child (by name) limited by parent term (Drupal 7).
<?php
/**
* Find taxonomy term (by name) limited by parent term.
*
* In many cases you may need to find children in exact term (parent).
* Here we do this in efficent way with precise query (not like taxonomy_get_tree()
* where all the terms loading.
*
* @param $name
* @param $parent
* @param $vid
*
* @return array
* Terms array or empty array if nothing found.
*/
function taxonomy_find_term_by_parent($name, $parent, $vid) {
$query = db_select('taxonomy_term_data', 't');
$query->join('taxonomy_term_hierarchy', 'h', 'h.tid = t.tid');
$result = $query
->addTag('translatable')
->addTag('taxonomy_term_access')
->fields('t')
->fields('h', array('parent'))
->condition('t.vid', $vid)
->condition('t.name', $name)
->condition('h.parent', $parent)
->orderBy('t.weight')
->orderBy('t.name')
->execute();
$terms = [];
foreach ($result as $term) {
$terms[$term->tid] = $term;
}
return $terms;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment