Created
November 20, 2013 17:23
-
-
Save cesarmiquel/7567231 to your computer and use it in GitHub Desktop.
Add term tree into a taxonomy
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
<?php | |
// Structure to use | |
$terms = array( | |
array('name' => 'Technical', 'weight' => 1, 'parent' => 0), | |
array('name' => 'Operations', 'weight' => 6, 'parent' => 0), | |
array('name' => 'Customer Relationship', 'weight' => 7, 'parent' => 0), | |
array('name' => 'Talent & Culture', 'weight' => 11, 'parent' => 0), | |
array('name' => 'Finance', 'weight' => 12, 'parent' => 0), | |
array('name' => 'Dev', 'weight' => 0, 'parent' => 'Technical'), | |
array('name' => 'QA', 'weight' => 1, 'parent' => 'Technical'), | |
array('name' => 'PM', 'weight' => 2, 'parent' => 'Technical'), | |
array('name' => 'BA', 'weight' => 3, 'parent' => 'Technical'), | |
array('name' => 'FE', 'weight' => 4, 'parent' => 'Technical'), | |
array('name' => 'Sales', 'weight' => 0, 'parent' => 'Customer Relationship'), | |
array('name' => 'BD', 'weight' => 1, 'parent' => 'Customer Relationship'), | |
array('name' => 'Marketing', 'weight' => 2, 'parent' => 'Customer Relationship'), | |
); | |
_add_taxonomy_tree($terms); | |
exit(0) | |
/** | |
* Add terms to $vocabulary given in array $terms. | |
* | |
* The $terms array has one or more arrayss with the following structure: | |
* | |
* array( | |
* array( | |
* 'name' => 'Term name', | |
* 'weight' => 1, | |
* 'parent' => '0 or the name of the parent term' | |
* ), | |
* ... | |
* ); | |
* | |
* @param $vacabulary_name Machine name of vocabulary | |
* @param $terms Term array structure. | |
*/ | |
function _add_taxonomy_tree($vocabulary_name, $terms) { | |
// Create taxonomy terms. It assumes just one parent per term | |
$voc = taxonomy_vocabulary_machine_name_load($vocabulary_name); | |
$vid = $voc->vid; | |
$all_terms = array(); | |
$tree = taxonomy_get_tree($vid); | |
foreach($tree as $tree_item) { | |
$all_terms[$tree_item->name] = $tree_item->tid; | |
} | |
foreach ($terms as $term) { | |
$term['vid'] = $vid; | |
if ($term['parent'] !== 0) { | |
$parent_name = $term['parent']; | |
if (isset($all_terms[$parent_name])) { | |
$term['parent'] = array($all_terms[$parent_name]); | |
} | |
} | |
$term = (object) $term; | |
taxonomy_term_save($term); | |
$all_terms[$term->name] = $term->tid; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment