I need to get the node alias during a hook_node_insert() when creating a brand new node. Function drupal_lookup_path() returns blank because the node actually isn't created yet per hook_node_insert() docs.

Does anyone know of a way to accomplish this or of an alternative to hook_node_insert().

  • What do you need the alias for? – David Thomas Sep 18 '15 at 1:07
  • I have a custom cross site posting script and want to set the canonical url. (I know you may ask why aren't you using Feeds but I have super complex logic that I had to implement it with Services) – albertski Sep 18 '15 at 1:11

A couple of options there, if drupal_lookup_path isn't returning the alias yet.

  1. Get the alias using pathauto_create_alias without the _pathauto_set_alias save part ( update: can use the 'return' option)
  2. Add the node id to a cron queue defined with hook_cron_queue_info and get/process the alias in a worker_callback a little later.
| improve this answer | |
  • Thanks you pointed me in the right direction. I was able to get the alias using the pathauto_create_alias() but using 'return' as the operation. – albertski Sep 18 '15 at 14:11

@David Thomas pointed me in the right direction with his answer. By passing 'return' as the operation to the pathauto_create_alias() function you can get the alias without saving the alias.

Here is my code:

 * Implements hook_node_insert().
function hcp_sync_node_insert($node) {

  module_load_include('inc', 'pathauto');
  $language =  pathauto_entity_language('node', $node);
  $uri = entity_uri('node', $node);
  $alias = pathauto_create_alias('node', 'return', $uri['path'], array('node' => $node), $node->type, $language);
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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