Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Magento getUrl not working with catalog/category object?

I've been able to instantiate a category object to retrieve its name, but when I use the getUrl method it isn't returning a URL to the category listing page, or anything at all

<?php
$children = Mage::getModel('catalog/category')->getCategories(3);
foreach ($children as $category):
            echo '<li><a href="' . $category->getUrl() . '">' . $category->getName() . '</a></li>';
        endforeach;
?> 

The code above results in HTML output of

<li><a href="">name of sub-cat</a></li>`

Does anyone know how I can get the URL for a category page from a catalog/category object?

like image 590
Kayla Avatar asked May 04 '11 23:05

Kayla


3 Answers

Replace

$children = Mage::getModel('catalog/category')->getCategories(3);

with

$children = Mage::getModel('catalog/category')->load(3)->getChildrenCategories();
like image 162
user487772 Avatar answered Nov 17 '22 22:11

user487772


The problem is getCategories() normally returns a Varien_Data_Tree_Node_Collection rather than a collection of categories. Instead, you can do this:

$children = Mage::getModel('catalog/category')->getCategories(3, 0, false, true);

The fourth parameter is $asCollection, passing a true means you are returned a Mage_Catalog_Model_Resource_Eav_Mysql4_Category_Collection which you were probably expecting. The rest should work now.

like image 36
clockworkgeek Avatar answered Nov 17 '22 22:11

clockworkgeek


You may load every category within the foreach loop and then get the category URL.

<?php
$children = Mage::getModel('catalog/category')->getCategories(3);
foreach ($children as $category): 
        $categoryUrl = Mage::getModel('catalog/category')->load($category->getEntityId())->getUrl();
        echo '<li><a href="' . $categoryUrl . '">' . $category->getName() . '</a></li>';
endforeach;
?>

This might work fine for less number of categories. However, this might take more time if you have large number of categories.

like image 41
Mukesh Chapagain Avatar answered Nov 17 '22 21:11

Mukesh Chapagain