1

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.

1

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()
      ->getItemDefinition()
      ->getSetting('target_type');
    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.

0

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()
  ->getStorage('taxonomy_term')
  ->loadMultiple($results);

$terms = [];

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

Note: this will only work with node entities.

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

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