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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
/** * @param $id * @return string */ public function getCategoryUrlById($id) { $requestPath = Mage::getSingleton('core/url_rewrite') ->getResource() ->getRequestPathByIdPath( 'category/' . $id, Mage::app()->getStore()->getId()); if(!empty($requestPath)) { return Mage::getBaseUrl() . $requestPath; } else { // Fallback: return Mage::getModel('catalog/category')->load($id)->getUrl(); } } |
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?
★ ★ ★ ★ ★
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]