·

photo credit: Oahu Lane via photopin (license)

Get Magento category URL without loading category

If you want to get the URL of Magento without actually loading the model, you can use Magento’s core URL rewrite functionality to fetch the URL without all too much load on the database like this:

I had to use this nifty trick once when I had to load a category tree that consisted of 9000+ categories, including their URL’s. Resolving the problem like this prevented a massive load on the server / database where more than 9000 category models where created.
The only ‘drawback’ of this method is that you need to have the URL of the category in your URL rewrite table (core_url_rewrite ), so that’s something to keep in mind. That’s the reason why there’s a fallback in the method, that gets the URL by loading the model.

Visitors give this article an average rating of 3.8 out of 5.

How would you rate this article?

One thought on “Get Magento category URL without loading category”

  1. Arvish says:

    This was really helpful. Thanks.

    In case needed, here’s my mod for getting either the name or the url…useful if you’re building individual links:

    [code]

    function getCategoryUrlById($id, $type =’url’)
    {
    $requestPath = Mage::getSingleton(‘core/url_rewrite’)
    ->getResource()
    ->getRequestPathByIdPath(
    ‘category/’ . $id, Mage::app()->getStore()->getId());

    if($type==’url’){

    if(!empty($requestPath))
    {
    return Mage::getBaseUrl() . $requestPath;
    } else {
    // Fallback:
    return Mage::getModel(‘catalog/category’)->load($id)->getUrl();
    }

    }
    elseif ($type==’name’) {
    return Mage::getModel(‘catalog/category’)->load($id)->getName();
    }
    }

    [/code]

Leave a Reply to Arvish Cancel reply