Drupal version from 7 to 9: How update an alias programmatically using a value from the field

18 Dec.2017
drupal - update an alias programmatically

When you use the "pathauto" module, and want to make the node's URL depends on your custom field you can create a pattern using a token, for example, [node:field_private:value] and the total pattern will look like articles/[node:field_private:value]/[node:title]. However, what can you do if the field is boolean but you want to make a human path/alias? In this case, you can implement it programmatically and alter using hook_pathauto_alias_alter.

 * Implements hook_pathauto_alias_alter().
function YOURMODULE_pathauto_alias_alter(&$alias, array &$context) {
  if ($context['module'] != 'node') {
  $node = $context['data']['node'];
  if ($node->hasField('field_private')) {
    if ($node->get('field_private')->getString() == 1) {
      $alias = '/for-members' . $alias;
    else {
      $alias = '/public' . $alias;

In the example, we are assuming your site has field_private. You can change this part of the code to your field's name.