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
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);
-
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
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')