Skip to main content

CREATING URL ALIAS through programming IN DRUPAL

Hi, I recently came across a peculiar use case: i had to create a logic where the URL alias changes when selecting a particular taxonomy term referenced in a particular content type.

Let's say for simplicity, that we have two types of URLs depending on the two possible taxonomies:

  • Taxonomy 1: \taxonomy_name\node:id\node:title.
  • Taxonomy 2: \taxonomy name\node:title

We had already made a pattern using pathauto in our Drupal 8 website, so we have to disable this pathauto configuration because now we will have the URL alias logic in our custom_module.module. We are going to use a hook, i.e. hook_Entity_TYPE_insert() or hook_Entity_TYPE_update(). Choosing the inserted hook or the update hook depends on your use case in your particular project.

* Implements hook_ENTITY_TYPE_insert().
function my_custom_module_node_insert(NodeInterface $node){

In this custom link, we are using the service to declare the URL path.

$path = \Drupal::service('path.alias_storage')->save("/node/" . $nid, "/".$tax_name."/" . $nid.'/'. $title, "en");

Hope this helps.