How do I get each taxonomy term associated to a node? I'm trying to add a preprocess hook to add classes based on taxonomy name to the body css of my drupal installation.  I've managed to get all the information about the node based on doing some searching around and trial and error, but I'd like to take it to the next step and get all the taxonomy terms based on the particular node id.

The code I am currently using is the following.

function custom_preprocess_html(&amp;$variables) {
  // Add the node ID and node type to the body class.
  $body_classes = [];
  $nodeFields =\Drupal::service('current_route_match')-&gt;getParameter('node')-&gt;toArray();

  if (is_array($nodeFields) &amp;&amp; count($nodeFields) &gt; 0) {
    if (isset($nodeFields['nid'])) {
      $body_classes[] = 'node-' . $nodeFields['nid'][0]['value'];
    }
    if (isset($nodeFields['type'])) {
      $body_classes[] = $nodeFields['type'][0]['target_id'];
    }
  }

  $variables['attributes']['class'] = $body_classes;
}


It works fine and pulls down the information regarding the node. Based on the answer here it seems like all I should have to do is add the following line to get the taxonomy terms: $taxonomyTerms = $nodefields-&gt;get('field_yourfield')-&gt;referencedEntities(); but when I do so Drupal throws an error. I'll freely admit I'm new to Drupal 8, so any suggestions about where I'm going wrong (is field_yourfield not something that exists, maybe?) would be greatly appreciated.
Don’t convert the node to an array, use the node object itself. Then methods will work.

// top of file...
use Drupal\node\NodeInterface;

function custom_preprocess_html(&amp;$variables) {
  $node = \Drupal::routeMatch()-&gt;getParameter('node');

  if ($node instanceof NodeInterface) {
    $type = $node-&gt;getType();
    $id = $node-&gt;id();
    $terms = $node-&gt;get('field_yourfield')-&gt;referencedEntities();
    // code here for $terms...

    $body_classes[] = 'node-' . $id;
    $body_classes[] = $type;
    // ... etc ...
  }
}


I assume type is node type.. but this is where you want to be. $terms should be a list of Term objects, so you can iterate and grab whatever data you need.

You should also check that the node type is the correct one before doing anything as well as checking for existence of the field to avoid errors.