What's the best way to get all taxonomy terms assigned to a node?

Should one use the taxonomy_index table?

Should one iterate through the fields on the node object?

I saw some answers for Drupal 7, but not for Drupal 8.


One way to do it is to iterate through each field and check if it's an entity_reference field with target type taxonomy_term, then extract the data you need.

$terms = [];

foreach ($node->getFields() as $key => $field) {
  if ($field->getFieldDefinition()->getType() == 'entity_reference') {
    $targetType = $field->getFieldDefinition()
    if ($targetType == 'taxonomy_term') {
      $new_terms = array_map(function (\Drupal\taxonomy\TermInterface $term) {
        return $term->label();
      }, $field->referencedEntities());
      $terms = array_merge($terms, $new_terms);

One advantage to this approach is it will work with any fieldable entity type.


One way to do it is with the taxonomy_index table:

$terms = [];

$query = \Drupal::database()
  ->select('taxonomy_index', 'ti')
  ->fields('ti', ['tid'])
  ->condition('nid', $node->id());

$results = $query->execute()->fetchCol();

$tids = \Drupal::entityTypeManager()

$terms = [];

foreach ($tids as $term) {
  $terms[] = $term->label();

Note: this will only work with node entities.

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.