A very recurring thing you would do is to get the current node id of the visited page. Here are two ways of doing it programmatically.

$entity = \Drupal::routeMatch()->getParameter('node');
if ($entity instanceof \Drupal\node\NodeInterface) { // Check if it is a node
  $nid = $node->id(); // You also have the node object right here

Slightly shorter and less good in my opinion is the following. Note that here there is no guarantee this is a node.

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


Saved you some valuable time?

Donate and get more free time-saving code on this website in the future.