How do I get the node url alias from the nid?

I have the nid: 37

I don't want: 'node/37' but 'my-custom-alias'

Comments

Anonymous’s picture

You can use the drupal_get_path_alias function e.g.

$alias = drupal_get_path_alias('node/37');

http://api.drupal.org/api/drupal/includes--path.inc/function/drupal_get_...

vivefree’s picture

thanks!

NoRandom’s picture

I know it's a pretty old question but since I just found it (6.5 years later!!!), I would like to add that at least in Drupal 7, nid = 0123 and nid = 123 are not the same for drupal_get_path_alias. So cast your variable to an integer before using it in the path. i.e.

    $nid = '023';
    $path = 'node/' . (int) $nid);
    $alias = drupal_get_path_alias($path); 

(In my site users can create "automatic" links to nodes by simply writing (#123), and I was trying to avoid that adding a leading zero broke the nice path aliases)

SivaprasadC’s picture

Small Typo correction.

    $nid = '023';
    $path = 'node/' . (int) $nid;
    $alias = drupal_get_path_alias($path); 
Aaron23’s picture

How to do in Drupal 8?

sunilajmani’s picture

You can below code to get alias in Drupal 8:

$path_alias = \Drupal::service('path.alias_manager')->getAliasByPath($system_path, $langcode);
pleclerc’s picture

function mythemename_preprocess_node(&$variables) {
$variables['path_alias'] = \Drupal::service('path.alias_manager')->getAliasByPath($system_path, $langcode);
}

I did that to reach the path in the twig {{ path_alias }}
but I have a error
InvalidArgumentException: Source path has to start with a slash. in Drupal\Core\Path\AliasManager->getAliasByPath() (line 186 of core/lib/Drupal/Core/Path/AliasManager.php).
espacedomicile_preprocess_node(Array, 'node', Array) (Line: 287)
Drupal\Core\Theme\ThemeManager->render('node', Array) (Line: 435)

swilmes’s picture

Try passing '/node/nid' as $system_path instead of 'node/nid'.

nimbfire@gmail.com’s picture

Full working example for Drupal 8:

<?php
$nid = 123;
$path = '/node/' . (int) $nid;
$langcode = \Drupal::languageManager()->getCurrentLanguage()->getId();
$path_alias = \Drupal::service('path.alias_manager')->getAliasByPath($path, $langcode);
?>

Its important to know that if you use the wrong language, the result will be different and does not trigger any warning or error.

So for example:

<?php
$nid = 123;
$path = '/node/' . (int) $nid;
$langcode = \Drupal::languageManager()->getCurrentLanguage()->getId(); // Gives something like /news/news-title
$langcode ='en'; // Gives something like /news/news-title
$langcode ='pt-br'; // Gives the node default path: /node/123
$langcode ='wrong'; // Gives the node default path: /node/123 too. AND DOES NOT GIVES ANY ERROR.
?>