Overriding Taxonomy Term Links in Drupal Modules

If you're writing a Drupal module that provides a custom node type, and you want to override, or just get rid of, the default display of taxonomy links (aka categories or tags), here is the solution.

Let's say, for example, that your custom node type has it's own way to display taxonomy terms, and you don't want Drupal to display them a second time at the bottom of the page (or wherever the theme you're using puts them). If you were writing a theme, you could create node-yourmodule.tpl.php and get rid of $terms, but for modules, there's a different solution: hook_link_alter.

Here's the code to implement the hook:

/**
* Implementation of hook_link_alter().
*/
function yourmodule_link_alter(&$links, $node) {
  // get rid of taxonomy term links
  if ($links->type == "yourmodule") {
    $links->taxonomy = array(); // empties the term links array.
  }
}

Obviously, you'll want to replace "yourmodule" with the name of your module.

You can also use hook_link_alter to alter other node types, for example:

/**
* Implementation of hook_link_alter().
*/
function yourmodule_link_alter(&$links, $node) {
  // get rid of taxonomy term links on story nodes
  if ($links->type == "story") {
    $links->taxonomy = array(); // empties the term links array.
  }
}

This hook can also be used to get rid of $links, which holds things like the "read more" and "add comments" links.

/**
* Implementation of hook_link_alter().
*/
function yourmodule_link_alter(&$links, $node) {
  // get rid of $links
  if ($links->type == "yourmodule") {
    $links->links = array(); // empties the $links array.
  }
}

This code could be modified to remove specific link items, rather than just emptying the $links array altogether. I'll leave that as an exercise for the reader. ;)

Note: This code was written with Drupal 5 in mind, and won't work with earlier versions because hook_link_alter doesn't exist in Drupal 4.7. All example code is covered by the GPL, so feel free to use it and not give me credit. :)

Posted by John on 2007-04-16