Drupal - Check content type of node in preprocess hook

To get the content type of a node, you just use $variables['node']->getType() or $variables['node']->bundle(). The first method just calls the second, so calling one or the other one doesn't make much difference.

public function getType() {
  return $this->bundle();
}

The only difference is that bundle() is defined for every entity, since the concept of bundle is common for all the entities, while content type is the property Drupal used for nodes before changing them in one of the entities Drupal core modules implement; using bundle() makes easier to adapt the code for other entity types, but I don't think it is the case for the code you are using.


You have to use $variables['node']->getType(). Also if you need it on some view modes only, consider doing a check on this as well, with $variables['view_mode']


You can add the node (and view type) to your hook function name:

function MYTHEME/MYMODULE_preprocess_node__nodetype__display(&$variables) {
  // ...
}

For example, for the page node type in full mode:

function MYTHEME/MYMODULE_preprocess_node__page__full(&$variables) {
  // ...
}

Tags:

Nodes

8

Hooks