Member-only story

How to Alter a Path in Drupal Before Saving Content

When you need a custom logic for URL generation

Sergio Guardiola Herrador
2 min readOct 1, 2024
Photo by Remotar Jobs on Unsplash

When using the module pathauto, it’s best to configure the patterns in this URL: admin/config/search/path/patterns and then export them to config. But it might not be enough if you need to implement a custom logic for the URL generation.

For that, you can use hook_pathauto_alias_alter, which alters pathauto-generated aliases before saving the content.

Here’s an example of something I had to do recently:

/**
* Implements hook_pathauto_alias_alter().
*/
function custom_module_pathauto_alias_alter(string &$alias, array &$context) {
// Ensure this is triggered for node content.
if ($context['module'] == 'node' && isset($context['data']['node'])) {
$node = $context['data']['node'];

// Check if the node has 'islands' field and it's not empty.
if ($node->hasField('islands') && !$node->get('islands')->isEmpty()) {
// Get the taxonomy term ID.
$term_id = $node->get('islands')->target_id;

// Load the taxonomy term entity to get its name.
$term = \Drupal\taxonomy\Entity\Term::load($term_id);
if ($term) {
// Get the taxonomy term name and replace spaces with hyphens.
$island_name = strtolower(str_replace(' ', '-', $term->getName()));

//…

--

--

Sergio Guardiola Herrador
Sergio Guardiola Herrador

Written by Sergio Guardiola Herrador

I write articles in English and Spanish, mostly about programming, technology, travel, money, investing. You can find me here: https://sergioguardiola.net

No responses yet