9

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?

Alana Storm
  • 164,128
  • 91
  • 395
  • 599
Kayla
  • 133
  • 1
  • 3
  • 9

3 Answers3

16

Replace

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

with

$children = Mage::getModel('catalog/category')->load(3)->getChildrenCategories();
user487772
  • 8,800
  • 5
  • 47
  • 72
6

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.

clockworkgeek
  • 37,650
  • 9
  • 89
  • 127
  • Thank you for your help! However I was looking to only display the first level children categories, which the two answers below took care of. Again, thank you so much for your help! – Kayla May 06 '11 at 04:35
  • For the sake of future readers you can control the depth of levels with the second parameter; instead of `0` put `1` for just the first level, `2` for first and second, etc. You are right that Gordon's answer does the same thing and is neater too. – clockworkgeek May 06 '11 at 11:14
  • Hi Clockworkgeek, Can you tell me how to add an if statement to say: if the catoegories have children, link to child category, if not, link normal category link. (For mobile site) – Geoff Feb 13 '12 at 18:33
3

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.

Mukesh Chapagain
  • 25,063
  • 15
  • 119
  • 120