2

I have been looking into entityQuery but haven't seen what I am trying to do yet.

If I have a node object, is it possible to get all taxonomy terms referenced by the node object, regardless of the field they are in?

Most of what I have seen would be getting the terms from a specific field, but I won't have access to the field name. I just need to find all terms in a specific vocabulary that are referenced by the node. Thanks!

  • 1
    Any solution for this problem will include looping on all the fields of said node and checking if they are a taxonomy reference field. – Eyal Jun 14 '16 at 7:21
  • Can you tell us the use case, why you can't be aware of the field name which referencing to the node? Maybe we could find another approach! Of course we can solve this one as well, but maybe that would be easier. – ssibal Jun 14 '16 at 7:40
  • I am looking at porting the Drupal 7 Parse.ly module and I need to add all the taxonomy terms of a specific vocabulary (or multiple) configured by the user to the metadata in the head of the page. I could add configuration to have the user give me the field name used, but was hoping there would be a good solution without that. – David C Jun 14 '16 at 13:32
1

You can iterate through all the fields on the node and add conditions to check that the field is an entity reference field, and that the target type is taxonomy_term:

// Iterate through each field on the node entity to get all the tagged
// taxonomy terms on the node.
foreach ($entity->getFields() as $field) {
  // Only look for fields that are entity reference fields.
  if ($field instanceof EntityReferenceFieldItemList) {
    // Get the field settings.
    $field_definition = $field->getFieldDefinition();
    $target_type = $field_definition->getSetting('target_type');
    // Check that the field targets are taxonomy terms.
    if ($target_type == 'taxonomy_term') {

      // Do stuff..

    }
  }
}

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.