Created
February 14, 2013 15:52
-
-
Save hannesl/4953693 to your computer and use it in GitHub Desktop.
A Drupal 7 helper function that takes a taxonomy term name and returns a corresponding term ID – even if it has to create the term first. Also supports adding Parent -> Child terms.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /** | |
| * Helper function to link term names to taxonomy terms, and create new terms | |
| * on-the-fly when necessary. | |
| * | |
| * @param $name | |
| * - The name of the taxonomy term. | |
| * @param $vocabulary_name | |
| * - The machine name of the vocabulary where the term should be stored. | |
| * @param $parent_name | |
| * - Optionally the name of the parent term. | |
| * @return | |
| * - The term id (tid). | |
| */ | |
| function _mymodule_get_taxo_term($name, $vocabulary_name, $parent_name = '') { | |
| // See if the term exists in the chosen vocabulary and return the tid. | |
| // If so, disregard the parent name to avoid duplicates. | |
| if ($possibilities = taxonomy_get_term_by_name($name, $vocabulary_name)) { | |
| $term = array_pop($possibilities); | |
| return $term->tid; | |
| } | |
| // Otherwise, create a new term and return the tid. | |
| elseif ($vocabulary = taxonomy_vocabulary_machine_name_load($vocabulary_name)) { | |
| // Handle parent term first, using a recursive call. | |
| if (!empty($parent_name)) { | |
| $parent_tid = _mymodule_get_taxo_term($parent_name, $vocabulary_name); | |
| } | |
| $term = (object) array( | |
| 'vid' => $vocabulary->vid, | |
| 'name' => trim($name), | |
| ); | |
| if ($parent_tid) { | |
| $term->parent = $parent_tid; | |
| } | |
| taxonomy_term_save($term); | |
| return $term->tid; | |
| } | |
| return false; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment