3

If I’m accessing an entry’s URL (the 4th check in Routing), how can I get the entry that the URL matched from a plugin?

3

You can get the request’s matched element via:

$element = craft()->urlManager->getMatchedElement();

There are two things to remember though:

  1. There may not be a matched element
  2. The matched element might not be an entry. (It could also be a category, and if you have any plugins installed that add their own element types that can have their own URLs, it could be one of those.)

To defend against those possibilities, just use the following conditional:

if ($element && $element->getElementType() == ElementType::Entry)
{
    // There was a matched element, and it's an entry!
    // ...
}
2
  • Will this work in elementapi when setting up end points? – joomkit Jul 20 '16 at 21:07
  • @joomkit No, in that case the matched element(s) are passed directly to your tranformer function, so there's no need to have a separate way to access them. If you're having trouble trying to get something set up please post as a new question :) – Brandon Kelly Jul 24 '16 at 13:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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