drupal 8 get node from path alias 1

drupal 8 get node from path alias

// Get node from path alias.
$path = \Drupal::service('path.alias_manager')->getPathByAlias('/this-is-the-alias');

if(preg_match('/node\/(\d+)/', $path, $matches)) {
  $node = \Drupal\node\Entity\Node::load($matches[1]);
}

// Path alias manager service has been change to 'path_alias.manager' on later version.
$path = \Drupal::service('path_alias.manager')->getPathByAlias('/this-is-the-alias');

Here is what the above code is Doing:
1. Get the path alias.
2. Check if the path alias is a node.
3. If it is a node, load the node.

Similar Posts