Query taxonomy terms with Drupal 8

Submitted by Randall Box on Fri, 04/03/2020 - 02:18

Sometimes you need to retrieve a list of taxonomy terms within code in Drupal 8.

use Drupal\taxonomy\Entity\Term;      
use Drupal\Core\Link;
use Drupal\Core\Url;

$vocabulary_name = 'tags';
$query = \Drupal::entityQuery('taxonomy_term');
$query->condition('vid', $vocabulary_name);
$query->sort('weight');
$tids = $query->execute();
$terms = Term::loadMultiple($tids);
foreach($terms as $term) {
  $tid = $term->id();
  $name = $term->getName();
  
  echo $tid.",".$name."\n";
}

If you are within a render context, for example, a web page, you may render the link instead with:

  $name = $term->getName();
  $url = Url::fromRoute('entity.taxonomy_term.canonical', ['taxonomy_term' => $term->id()]);
  $link = Link::fromTextAndUrl($name, $url);
  $link = $link->toRenderable();
  render($link);

 

Technology