2

I'm working a plugin and part of the task is to grab the entry based on the current URI using craft()->request->getRequestUri().

Is there a way to grab the entry based on the URI from the request?

2

You can grab the current entry using the $uri = craft()->request->getRequestUri() which will return the URI in a format like so:

/path/to/uri

To grab the entry, its easiest to grab the element first, based on the URI, using craft()->elements->getElementByUri($uri). However, this will not work because of the beginning slash that is returned by getRequestUri. So you must remove the slash using ltrim like so:

$uri = ltrim(craft()->request->getRequestUri(), '/')

Once you have the URI, minus the beginning slash (path/to/uri), you can use $element = craft()->elements->getElementByUri($uri) to return the element and then grab the entry using $entry = craft()->entries->getEntryById($element->id).

If you were going to need this often, you can place it in a helper method on the controller.

private function getEntryByRequestUri()
{
    // remove the first trailing slash
    $uri = ltrim(craft()->request->getRequestUri(), '/');
    $element = craft()->elements->getElementByUri($uri);
    $entry = craft()->entries->getEntryById($element->id);
    if ($entry == null) {
        // log something and do something
    }
    return $entry;
}

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.