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
I usually do something like this:
<?php
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.