Skip to content

Instantly share code, notes, and snippets.

@megclaypool
Last active April 4, 2025 19:03
Show Gist options
  • Save megclaypool/6d7c972c72a5e2f55564474b83af5705 to your computer and use it in GitHub Desktop.
Save megclaypool/6d7c972c72a5e2f55564474b83af5705 to your computer and use it in GitHub Desktop.

Ok, so

  • $thingie is your node, or paragraph, or whatever. You're probably writing this code in your thingie's preprocess hook
  • field_reference is the entity reference field that's referring to your taxonomy term whose inner data you want to plunder
  • desired_field is the actual field inside the taxonomy term whose data you need
// Make sure the field exists and isn't empty
if ($thingie->hasField('field_reference') && !$thingie->get('field_reference')->isEmpty()) {
  // This is a taxonomy term reference, so I need to get the term id, then load it to get the term data.
  $termreference = $thingie->get('field_reference')->target_id;
  $term = \Drupal::entityTypeManager()->getStorage('taxonomy_term')->load($termreference);
  // Now you can plunder the term for data :)
  ($term->hasField('desired_field') && !$term->get('desired_field')->isEmpty()) {
    $desired_field = $term->get('desired_field')->value;
    $variables['desired_field'] = $desired_field;
    // or maybe you just wanted the term name
    $name = $term->getName();
  }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment