0

I want to show the term names used in a node. My term field machine name is field_category.

$query = \Drupal::entityQuery('node');
$query->condition('status', 1);
$query->condition('type', 'content_type');
$entity_ids = $query->execute();
$nodes = \Drupal::entityTypeManager()->getStorage('node')->loadMultiple($entity_ids);
foreach ($nodes as $node) {
   dpm($node);
}

dpm() prints the following.

stdClass Object(
[__CLASS__] => Drupal\node\Entity\Node
[in_preview] => 
[values] => Array
 [field_category] => Array
            (
                [x-default] => Array
                    (
                        [0] => Array
                            (
                                [target_id] => 4
                            )

                        [1] => Array
                            (
                                [target_id] => 2
                            )

                    )

            )

How can I print the term names as term-1,term-2?

1 Answer 1

3

You can do this:

foreach($nodes as $node) {
  $categories = $node->field_category->referencedEntities();
  foreach($categories as $category) {
    print_r($category->getName(). ",");
  }
  print("\n");
}
1
  • 2
    Using the field items is IMHO simpler: foreach ($node->field_category as $item) { print $item->entity->getName(); }. Don't forget an if ($item->entity) check however, as it is possible that you have a dead reference.
    – Berdir
    Oct 12, 2016 at 18:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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