Please Disable Your Browser Adblock Extension for our site and Refresh This Page!

our ads are user friendly, we do not serve popup ads. We serve responsible ads!

Refresh Page
Skip to main content
On . By CodimTh
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();

  }
}

Tags :

Comments

Add new comment

Restricted HTML

Search

Page Facebook

Become a patron

If you need some help or you search a Drupal freelancer don't hesitate to contact us.

 

Contact Us

All the content is FREE but I still need your help

 

Become a patreon