1

Wondered what the best approach would be to get the url for a given entry page using only a slug for reference? I imagined it being something like this:

 public function getPageURL($slug) {
    $page = craft()->elements->slug($slug);
    @return getURL($page);
  }

Usage example:

<a href="{{ craft.PLUGINNAME.getPageURL("staff") }}">Staff</a>
2

Completely untested, but something like this should work:

public function getPageUrl($slug)
{
    $criteria = craft()->elements->getCriteria(ElementType::Entry);
    $criteria->slug = $slug;
    $entry = $criteria->first();

    if ($entry)
    {
        return UrlHelper::getUrl($entry->uri);
    }
}
|improve this answer|||||
  • Thanks again Brad, that's the second time you've pointed me in the direction of the Helpers. buildwithcraft.com/classreference#craft.app.helpers – Mark Notton Nov 19 '14 at 10:44
  • 1
    You can even simplify that by just invoking the getUrl() method on the $entry object. There's no need for calling the UrlHelper (the getUrl() method is already using it). So, you can shorten the last line to this: return $entry->getUrl(); – Arvid Jul 14 '15 at 13:05

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.