I'm trying to get run some code if the content type of the current page is equal to events. I am using Drupal 8.

However, I'm unable to write the if statement.

I've tried:

if ($node->type == 'events'){...}
if (Node::getType == 'events'){...}

I also saw this question, but I have no idea how to apply it.

Full code:

// Add og:event:start_date meta tag

function MY_THEME_preprocess_html(&$variables) {
  if ($node->getType() == 'events'){
    $time = [
      '#tag' => 'meta',
      '#attributes' => [
        'http-equiv' => 'og:event:start_date',
        'content' =>  $node->field_next_time->value,

    $variables['page']['#attached']['html_head'][] = [$time, 'og:event:start_date'];  


1 Answer 1


You need to pull the node object out of the variables array.

$node = $variables['node'];

In certain preprocess functions this may not be available, so you can try the request service:

$node = \Drupal::request()->get('node');

The object must be of type Node. Therefore:

$node->getType() == 'events'

As Berdir mentioned, you should check and ensure that $node is a valid Node object to see if it is an instance of NodeInterface before operating on it. This will prevent fatal errors in the event that $variables['node'] is actually a node and not some ad-hoc variable created in code from which you can't call methods on:

Example 1 (using $variables array):

if (isset($variables['node']) && $variables['node'] instanceof NodeInterface) {
  $node = $variables['node'];
  $title = $node->getTitle();
  $type = $node->getType();
  // more code...

Example 2 (using the request):

$node = \Drupal::request()->get('node');

if (isset($node) && $node instanceof NodeInterface) {
  $title = $node->getTitle();
  $type = $node->getType();
  // more code...
  • Thanks, but I'm getting Fatal error: Call to a member function getType() on a non-object. Also, var_dump($node); returns NULL Apr 27, 2017 at 22:48
  • Because node has not been assigned. See updated answer.
    – Kevin
    Apr 27, 2017 at 23:00
  • 1
    you should always include an $node instanceof NodeInterface check, when getting it from the request as not all pages have a node. As well as an isset() on $variables when using that.
    – Berdir
    Apr 28, 2017 at 19:39
  • Good info, updated.
    – Kevin
    Apr 28, 2017 at 19:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.