Skip to main content
Category:

in this post, I'll show you how do I get the current node ID in drupal 8.

<?php

/**
 * @param $variables
 */
function mymodule_preprocess_page(&$variables) {

  $route_name = \Drupal::routeMatch()->getRouteName();
  if ($route_name == 'entity.node.canonical') {

    /**
     * method 1
     */
    $entity = \Drupal::routeMatch()->getParameter('node');
    if ($entity instanceof \Drupal\node\NodeInterface) {
      $nid = $entity->id();
    }

    /**
     * method 2
     */
    $node = \Drupal::routeMatch()->getParameter('node');
    $nid = $node->id();

  } elseif ($route_name == 'entity.node.preview') {

    /**
     * Example for node preview page
     */
    $node = \Drupal::routeMatch()->getParameter('node_preview');
    $nid = $node->id();

  }
}

Riadh Rahmi

Senior Web Developer PHP/Drupal & Laravel

I am a senior web developer, I have experience in planning and developing large scale dynamic web solutions especially in Drupal & Laravel.

Web Posts

Search

Page Facebook