Drupal - Create path alias programatically when node is created

Instead of using hook, Pathauto module should be used where you can define specific pattern how aliases are generated per content type (at /admin/config/search/path/patterns). In there you can use replacement patterns or code your own. It's much cleaner approach.

Otherwise you can try hook_node_presave($node) and change the alias directly:

$node->path['pathauto'] = 0; // Required only if Pathauto is enabled.
$node->path['alias'] = "foo/bar";

or use the path_save(&$path) function directly as below:

$path = array('source' => "node/$node->nid", 'alias' => 'foo/bar');
path_save($path);

The function is now called path_save(), see path_taxonomy_term_insert() for an example.


hook_node_insert() wasn't working in my case, and with some searches I came up with this blog post. I implemented hook_insert() in the same way and presto.

/**
 * Implements hook_insert().
 */
function mymodule_insert($node) {
    // Set the URL alias
    if (empty($node->path['alias'])) {
        $node->path['alias'] = 'slug/' . $node->nid;
    }
}