3

I'm trying to rewrite the URL of a node. I have the following test code:

function mymodule_url_outbound_alter(&$path, &$options, $original_path) {

    if ($path == 'testpage') {
        $path = 'test-alias';
        $options['alias'] = $path;
    }
}

Which doesn't seem to do anything when I visit /testpage or /test-alias. It's definitely executing the code inside the if statement. Am I doing something wrong here?

I have previously implemented hook_url_inbound_alter(), which works perfectly and doesn't do anything on this particular page. I also use the Path module.

2
  • Are you sure you are understanding the use of outbound url alters? Unless I am being dense this morning (totally possible) outbound alters changes urls that drupal creates, eg, via its url() function, that are then subsequently embedded in html/pages/etc. Thus it wouldn't do anything if you actually typed in a url into your browser.
    – Jimajamma
    Commented Jan 12, 2014 at 18:16
  • It is very likely I am using it wrong. As I understand it, I can use outbound_alter to create an alias for a given path.
    – Koozer
    Commented Jan 12, 2014 at 18:49

1 Answer 1

5

If you want to create an alias using hook_url_outbound_alter(), you need to implement also hook_url_inbound_alter(), since the former is for links output from Drupal, and the latter is for links received from Drupal. The former changes the path with its alias, while the latter changes the alias with the equivalent path.

Keep in mind that:

  • If you are not doing conditional replacements, then it is probably less performance-heavy to use the normal Drupal path aliases

  • Between the arguments taken from hook_url_outbound_alter(), $path is the path as already changed by the previously executed module, while $original_path is the path before being changed from any module

Also, $options['alias'] is really a boolean, not a string, which tells url() whenever the path being passed to the function is already a path alias. In the case it is, drupal_get_path_alias() will not be called.

2
  • 1
    I have it working now with hook_url_inbound_alter() { if ($path == 'test-alias') { $path = 'node/1234';}. I'm still not entirely sure how it works though... I also can't find information on $options anywhere - my ultimate goal is to rewrite queries. I accepted your answer as it does solve the particular question I asked.
    – Koozer
    Commented Jan 13, 2014 at 20:42
  • 2
    $options is the same argument taken from url().
    – avpaderno
    Commented Jan 13, 2014 at 21:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.