You are here

function token_taxonomy_term_load_all_parents in Token 8

Same name and namespace in other branches
  1. 7 token.module \token_taxonomy_term_load_all_parents()

Loads all the parents of the term in the specified language.

Parameters

int $tid: The term id.

string $langcode: The language code.

Return value

string[] The term parents collection.

1 call to token_taxonomy_term_load_all_parents()
token_tokens in ./token.tokens.inc
Implements hook_tokens().

File

./token.module, line 557
Enhances the token API in core: adds a browseable UI, missing tokens, etc.

Code

function token_taxonomy_term_load_all_parents($tid, $langcode) {
  $cache =& drupal_static(__FUNCTION__, []);
  if (!is_numeric($tid)) {
    return [];
  }
  if (!isset($cache[$langcode][$tid])) {
    $cache[$langcode][$tid] = [];

    /** @var \Drupal\taxonomy\TermStorageInterface $term_storage */
    $term_storage = \Drupal::entityTypeManager()
      ->getStorage('taxonomy_term');
    $parents = $term_storage
      ->loadAllParents($tid);

    // Remove this term from the array.
    array_shift($parents);
    $parents = array_reverse($parents);
    foreach ($parents as $term) {
      $translation = \Drupal::service('entity.repository')
        ->getTranslationFromContext($term, $langcode);
      $cache[$langcode][$tid][$term
        ->id()] = $translation
        ->label();
    }
  }
  return $cache[$langcode][$tid];
}