Is it possible to query the current entry or category element via a Craft 3 plugin/module?

In the 2.6 era, I would use a hook. The Craft 3 iteration of a hook looks something like this:


Craft::$app->getView()->hook('someHook', function(array &$context) {
  if (isset($context['entry'])) {
    $currentElement = $context['entry'];
  } else if (isset($context['category'])) {
    $currentElement = $context['category'];

With an accompanying Twig snippet in the template:

{% hook 'someHook' %}

I'm wondering if there is a cleaner practice to accomplish the same goal? I find relying on Twig snippet reduces the flexibility of my plugin.

I've noticed the SEOMatic plugin is able to append entry specific data without any hooks in the template. I can't figure out how, but it gives me hope.

1 Answer 1


Check out Craft::$app->getElements()->getElementByUri() -- or you might also use Craft::$app->getUrlManager()->getMatchedElement() depending on your use case.

  • Your friendly neighborhood SEOmatic author :)
  • From the man himself! Thanks Andrew, this is exactly what I've bene after. Commented Apr 21, 2018 at 22:06
  • No prob. Updated the answer with another possibility for you too, depending on what you're trying to do. Commented Apr 23, 2018 at 1:22

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.