I have a taxonomy menu, and I want to redirect the page request from taxonomy/term/% to a custom path using a page callback function. How can I use a function to cause the redirect?
2 Answers
If I understand you want to implement hook_menu_alter()
and override the page callback
for that path:
function MYMODULE_menu_alter(&$items) {
$items['taxonomy/term/%taxonomy_term']['page callback'] = 'MYMODULE_taxonomy_page_callback';
}
function MYMODULE_taxonomy_page_callback($term) {
// Either redirect the page
drupal_goto('somewhere');
// Or build up some output to replace the original taxonomy term page.
// This way you won't actually have to do a redirect at all
}
If I can offer a bit of advice, keep this callback function in your module file so it's always included. Otherwise you'll need to change the file
property of the menu item too and that can get quite messy as Drupal is expecting the file to exist in the path that the defining module is in (in this case the taxonomy module).
-
In your example, the callback function takes $term as an argument. Doesn't that mean that a 'page argument' must also be passed in the hook_menu_alter? I believe the line: $items[...['page arguments'] = array (2); should be added.– AshlarCommented Mar 15, 2012 at 19:54
-
2Don't forget you're altering an existing menu item...the taxonomy module has already set
'page arguments' => array(2)
in it's implementation ofhook_menu()
. Unless you (or another module) specifically unsets thepage arguments
inhook_menu_alter()
then the original ones will still be there– Clive ♦Commented Mar 15, 2012 at 20:03
I know you specifically asked about using a page callback function, but the more general question (emphasized in the question title) is simply to redirect a taxonomy term to a custom path/page. For that, the Page Manager module (part of CTools) is a great tool. It may help many people who want to accomplish the generic case, but don't know how or simply don't want to use a page callback function. There's also a great set of videos about Page Manager on Drupalize.me. At the time of this writing, those videos are free, not sure if that will change at some point.
-
Thanks. I am aware of page manager, but also thought it is time I dive into coding for Drupal and using hooks.– AshlarCommented Mar 22, 2012 at 14:31