Drupal and Web Development Tidbits

Load A Node Via Url Alias

May 9, 2020

Written by: Jon Kamke

How to load a Node object from a URL.

Snippet of code that will load a node object using the URL alias path and get the content type.

 /** @var Drupal\Core\Url $url */
 $url = $variables['url'];
   if ($url instanceof Drupal\Core\Url) {
     $nid = $url->getRouteParameters()['node'];
     /** @var \Drupal\node\Entity\Node $node */
     $node = Node::load($nid);
     if ($node instanceof Node) {
       $type = $node->getType();
     }
   }

The Github Gist: Load A Node Using URL Alias

Drupal-8

Node

Snippet