40

I know I can load a node by its title with the node_load() function. Is it possible to load a node by its URL alias?

2 Answers 2

60

You want to investigate menu_get_object and drupal_lookup_path.

Something like this would do what you want:

$alias = "some/path/to/a/page";
$path = drupal_lookup_path("source", $alias);
$node = menu_get_object("node", 1, $path);
2
  • Also, to dynamically grab url alias do next: $alias = $_SERVER['REQUEST_URI']; $alias = substr($alias, 1); // to remove "/" from beginning of string Jul 21, 2016 at 20:55
  • 1
    @EugenePavlov - $alias = drupal_get_path_alias(); should be it.
    – leymannx
    Apr 5, 2017 at 10:57
2

For somebody looking to find how to do this in Drupal 8 here is the corresponding question and answer

How can I get the node ID from a path alias?

use \Drupal\Core\Url;

$alias = \Drupal::service('path.alias_manager')->getPathByAlias('/etapes-de-la-vie');
$params = Url::fromUri("internal:" . $alias)->getRouteParameters();
$entity_type = key($params);
$node = \Drupal::entityTypeManager()->getStorage($entity_type)->load($params[$entity_type]);

For Drupal 9 use \Drupal::service('path_alias.manager') instead of \Drupal::service('path.alias_manager')

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.