10

I have a custom content type that is created by a module. Is there a hook I can use to set the path alias of my custom content type when a node is created?

One of my fields is an alpha-numeric code, and I want to use that in the path. eg.: 'event/myc0d3'

I noticed that this function (path_set_alias) existed in 6, but I can't find the equivalent for 7. And do not know where I would call it.

4 Answers 4

12

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);
1
  • For me only both in combination worked, so that in the end inside the alias textfield the right alias is written. Doing only path_save() worked but then I had the wrong alias in the alias textfield on node edit, so a simple resave would have gotten me the wrong alias again.
    – leymannx
    Sep 10, 2015 at 16:00
9

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

1
  • 4
    you should really expand this answer to not just link to offsite resources, however the links, as long as they stay valid, were useful.
    – DrCord
    Jul 2, 2014 at 22:03
9

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;
    }
}
2
  • 2
    To notice that hook_insert() is used only when the module implementing it is defining a content type; the hook cannot be used to act on a node for a content type defined from another module.
    – apaderno
    Nov 7, 2011 at 11:23
  • this is exactly the reason why it's not recommended to just link up to articles, but to expand on the answer instead and extract the main useful information from those articles - that 'blog post' link is no longer valid and results in a 404
    – Titi
    Feb 10, 2017 at 15:44
0

Implement hook_node_insert().

Your Answer

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

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