0

I have come up with a need to show a node term's URL alias using plain php in drupal 8 but I can't figure out how to do it. In my custom module, I want to get /fruits/apples in a variable upon loading a node which is linked with Fruits term.

Here you can see the Edit Term settings page in which I have set the URL alias of the term Fruits to /fruits/apples. I want to get this URL alias whenever a user loads a page linked to this term.

term url alias

  • 1
    I'm not sure I understand what you are trying to do but have a look at $path = \Drupal::service('path.alias_storage')->load([ 'source' => '/' . $node->urlInfo()->getInternalPath(), 'langcode' => $langcode ]); – user21641 Nov 15 '17 at 23:24
  • @IvanJaros I want to get the URL alias of the term. The picture shows the Edit Term Page in which you can see the URL alias assigned to the term Fruits. – Shujaat Ali Khan Nov 15 '17 at 23:38
  • @IvanJaros I have updated the question with some more details. – Shujaat Ali Khan Nov 15 '17 at 23:46
  • 1
    But why is the path necessary on a node form? When the terms display on a node page, they’ll be linked. – Kevin Nov 16 '17 at 5:25
2

You can get it by this way as well (assuming you know $id in advance in code) as of Drupal 8.5.x: 1. For taxonomy term:

Term::load($id); //not important
$aliasManager = \Drupal::service('path.alias_manager');
$alias = $aliasManager->getAliasByPath('/taxonomy/term/'.$id);

2. For node:

$node = \Drupal::entityManager()->getStorage('node')->load($id); //not important
$aliasManager = \Drupal::service('path.alias_manager');
$alias = $aliasManager->getAliasByPath('/node/'.$id);

OUTPUT: $alias = /fruits/apples

  • Thank you for the answer. One thing that helps is to use code formatting on code blocks. You can do this manually by indenting the code or highlight all the code and click the code button (looks like curly braces: { }). – mradcliffe Jan 14 at 13:46

Your Answer

By clicking "Post Your Answer", you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.