At a client this week, I struggled to find an easy way to change the links to all taxonomy terms. I tried using template_preprocess_field(), but that only covered the uses of taxonomy terms with fields. Taxonomy terms can be used in other places and it simply didn't make sense to involve the Field API; there must be something more universal.
Solution
In Drupal 7 the entity system treats nodes, taxonomy, users, and comments are essentially equal objects. All have URLs that are generated by single functions. It's easy to change all of these by modifying the URI callback of a single entity type. hook_entity_info_alter() makes that possible -
<?php
/**
* Implementation of hook_entity_info_alter().
*
* Redirect any links to program taxonomy terms to their corresponding node page.
*/
function mymodule_entity_info_alter(&$entity_info) {
$entity_info['taxonomy_term']['uri callback'] = 'mymodule_taxonomy_term_uri';
}
?>After doing this, we can easily change any internal taxonomy paths that we choose -
<?php
/**
* Entity uri callback for taxonomy terms. Add special exception to redirect users away
* from taxonomy term pages to the associated program node page.
*/
function mymodule_taxonomy_term_uri($term) {
if ('program' == $term->vocabulary_machine_name) {
$program_node_nids = field_get_items('taxonomy_term', $term, 'field_program_node');
return array(
'path' => 'node/' . $program_node_nids[0]['nid'],
);
}
else {
return array(
'path' => 'taxonomy/term/' . $term->tid,
);
}
}
?>

Add new comment