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();
}
}