Drupal 8/7 how to alter a path alias depending on a node property (field)

Profile picture for user a.berramou
Azz-eddine BERRAMOU 26 March, 2020

Pathauto module is one of the most used Drupal modules, it gives you the ability to generates URL/path aliases for various kinds of content (nodes, taxonomy terms, users) without requiring the user to manually specify the path alias.

But in some case you need to alter the path alias based on some content property/field like the use case described in this question.

This can easily be achieved from a custom module by implementing hook_pathauto_alias_alter.

<?php
/**
 * Implements hook_pathauto_alias_alter().
 */
function MODULE_NAME_pathauto_alias_alter(&$alias, array &$context) {
   // Check if the content is node and the bundle is an article. 
   if ($context['module'] === 'node' && $context['bundle'] === 'article') {
    /** @var \Drupal\node\Entity\Node $node */
    $node = $context['data']['node'];
    // Clean string service.
    $clean_string_service = \Drupal::service('pathauto.alias_cleaner');
    // Get the field value.
    $is_premium = $node->field_is_article_premium->value;
    //   If your field is checked.
    if ($is_premium === 1) {
      $alias = '/premium-article/' . $clean_string_service->cleanString($node->label());
    }
    else {
      $alias = '/normal-article/' . $clean_string_service->cleanString($node->label());
    }
  }
}

In the example above, I alter the path alias of articles based on the value of  field_is_article_premium field, if it's checked i set the path alias to premium-article/[article title] otherwise i set the path alias to normal-article/[article title].

The implementing example for Nodes you can do the same with Taxonomy terms and Users!

Note: First of all you should have configured the path alias for this content type from admin/config/search/path/patterns.

You are done ✅