TransWikia.com

Alter a path alias depending on a node property

Drupal Answers Asked by Fizzz69 on October 26, 2021

I use the Pathauto module and I’m trying to get, for the same content type, two different path aliases depending on a Boolean field that content type has.

I would like to have a path alias like mysite/node_name if the Boolean field value is false and mysite/[a generic term]/node_name if its value is true.

Is there a way to do this?

One Answer

if you don't won’t to create a new token as @Clive mentioned in comment, you can use hook_pathauto_alias_alter in your custom module like the following.

/**
 * Implements hook_pathauto_alias_alter().
 */
function MY_MODULE_pathauto_alias_alter(&$alias, array &$context) {
  if ($context['module'] === 'node' && $context['bundle'] === 'MY_BUNDLE') {
    // Get the node.
    $node = $context['data']['node'];

    // Clean string service.
    $clean_string_service = Drupal::service('pathauto.alias_cleaner');

    $is_checked = $node->field_SOME_NAME->value;
    //   If your field is checked.
    if ($is_checked === 1) {
      $alias = '/mysite/term/' . $clean_string_service->cleanString($node->label());
    }
    else {
      $alias = '/mysite/' . $clean_string_service->cleanString($node->label());
    }
  }
}

Answered by berramou on October 26, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP