Altering urls in Drupal

One of the great things about Drupal's taxonomy system is that category lists are generating automatically, just by tagging your content. The taxonomy module, creates a listing of the most recent nodes in each category using a path like taxonomy/term/23.

The Views module will allow you to override this default taxonomy listing and soup it up to your tastes. However, what do you do when you want to customize a special page for just one term?

On the newspaper sites that I work on we use Panels to create highly customized "home pages" for the some of the core news terms, like Sports for example. The Sports panel page will have a simple path of /sports and is linked to in the primary menu of a site, but we have a problem in that there are currently 2 sports pages. One is the custom Panels page:

/sports

and the other the taxonomy listing page:

/taxonomy/term/23

Since we created a custom sports page, we really want the taxonomy term page to just go away, but it shows up in links section of a node with other term links, as well as other places.

I finally found a straightforward solution to the problem that has it's source in a special Drupal function called custom_url_rewrite_outbound(). This special function is called inside the url() function and can be used to modify urls before they are output to the page. The API page for the function shows some great examples. According to the documentation, the function was intended to be placed in a settings.php file, but I found a module called URL Alter that implements this special function into a special hook callback that makes the functionality easily accessible to other modules and even via the admin interface.

function hook_url_outbound_alter(&$path, &$options, $original_path) {
  // Sport term should point to a customized Sports panels page
  if ($path == 'taxonomy/term/23') {
    $path = 'sports';
  }
}

With the URL alter module installed, the above function placed inside a module will convert all our Sports taxonomy links into the page for the custom Sports panel page. Pretty cool huh?

This will ensure, that no links on the site will point to the taxonomy listing page, even though it still exists and can be accessed directly (some users may have already bookmarked this page). To be thorough, it would be helpful to redirect the taxonomy/term/23 url to our Sports page using the Path Redirect module.

As a side note, the hook_url_outbound_alter() function has made it's way into the core of Drupal 7.