I'm trying to redirect users from an existing path in Drupal 7 to another existing path. I want to implement the following rule:
comment/reply/123
should redirect to node/123#comment-form
But
comment/reply/123/456
should NOT redirect anywhere and just go where it goes.
I've tried to implement this behavior with hook_menu(), but here's the problem. When I register an item with the path 'comment/reply/%'
that corresponds to comment/reply/123
, it automatically includes paths like comment/reply/123/456
. I know that's intended and changed my code to include this case, but can't figure out how to redirect users only when they hit comment/reply/123
. Here's my code:
function mymodule_menu()
{
$items = array();
$items['comment/reply/%/%'] = array(
'title' => 'bla',
'page callback' => '_mymodule_redirect',
'page arguments' => array(2, 3),
'access callback' => TRUE,
'type' => MENU_CALLBACK,
);
return $items;
}
function _mymodule_redirect($node_id, $comment_id)
{
if(isset($comment_id))
{
return; //I want to just go to comment/reply/123/456 here, but it gives me a blank page
}
else
{
drupal_goto('node/' . $node_id . '#comment-form');
}
}
So how do I go where I want to go?
Update: This is my final solution: I now use hook_menu_alter()
to rewrite an already defined link and comment_reply()
to serve standard comment form.
function mymodule_menu_alter(&$items)
{
$items['comment/reply/%node']['page callback'] = '_mymodule_redirect';
}
function _mymodule_redirect($node, $pid = NULL)
{
if(isset($pid))
{
return comment_reply($node, $pid);
}
else
{
drupal_goto(drupal_get_path_alias('node/' . $node->nid), array('fragment' => 'comment-form'), 301);
}
}