I've seen this question posted many places, but no answers - or relevant answer. i.e. how to get term object or ID from path or alias e.g. /cat/subcat or /taxonomy/term/6??


3 Answers 3


I usually do something like this:


use Drupal\taxonomy\Entity\Term;

function hook_preprocess_page(&$vars) {
  $route = \Drupal::routeMatch();
  if ($route->getRouteName() == 'entity.taxonomy_term.canonical') {
    $term_id = $route->getRawParameter('taxonomy_term');
    $term = Term::load($term_id);

For each entity type you can use like here to get entity object:

$term = \Drupal::request()->attributes->get('taxonomy_term');


If you are using original path not URL alias then you can explode you path like that

$exp = explode('/','/taxonomy/term/6');
$tid = $exp[2];

Then you can load your term object using this tid as@Ronnie say.

Your Answer

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

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