I needed this to only copy the root term over to another node. The rules module only have the parent value but how to drill down? This is what I did with Drupal 7.
/**
* Implements hook_rules_action_info().
*/
function my_custom_rules_action_info() {
return array(
'my_custom_get_root_term' => array(
'label' => t('Get root term'),
'parameter' => array(
'tid' => array(
'type' => 'taxonomy_term',
'label' => t('Term'),
),
),
'provides' => array(
'rootterm' => array(
'type' => 'taxonomy_term',
'label' => t('Root term'),
)
),
'group' => t('My custom rules'),
'base' => 'my_custom_rules_action_get_root_term',
),
);
}
/**
* Find the root term for the given $term.
*
* @param $term
*/
function my_custom_rules_action_get_root_term($term) {
$results = drupal_static(__FUNCTION__, array());
if (!is_object($term)) {
$term = taxonomy_term_load($term);
}
if (empty($term)) {
return;
}
// Build hash [$child] = $parent
if (!isset($result[$term->tid])) {
$tree = taxonomy_get_tree($term->vid);
foreach ($tree as $tree_term) {
// HUH: parents array always has one element on our vocabulary sets
// No parent == 0
$result = array_shift($tree_term->parents);
echo $result . PHP_EOL;
$results[$tree_term->tid] = $result;
}
}
// follow the parent refs until $parent == 0
$tid = $term->tid;
while ($results[$tid] != 0) {
$tid = $results[$tid];
}
return array('rootterm' => taxonomy_term_load($tid));
}
page--taxonomy.tpl.php
for this instance.