Magento Custom Category Listing Block

Here I wanted to show you how to build a custom Magento category listing block that you can use on your own Magento store. We will go over each step at getting a category listing of your magneto categories and even a sub category listing.

Here is the finished code for your new category listing block.

<?php
$cats = Mage::getModel('catalog/category')->load(2)->getChildren();
$catIds = explode(',',$cats);
?>
<ul>
<?php foreach($catIds as $catId): ?>
	<li>
    	<?php
			$category = Mage::getModel('catalog/category')->load($catId);
			echo $category->getName();

			$subCats = Mage::getModel('catalog/category')->load($category->getId())->getChildren();
			$subCatIds = explode(',',$subCats);
		?>
            <?php if(count($subCatIds) > 1):?>
                <ul>
                <?php foreach($subCatIds as $subCat) :?>
                    <li>
                    <?php
                        $subCategory = Mage::getModel('catalog/category')->load($subCat);
                        echo $subCategory->getName();
                    ?>
                    </li>
                <?php endforeach;?>
                </ul>
            <?php endif; ?>
    </li>
<?php endforeach; ?>
</ul>

And The XML Block Code:

<block type="catalog/navigation" name="catalog.category" template="catalog/navigation/category.phtml" />

NOTE:
After loading each category you have a whole array of different attributes you can use. If you wanted to make each category listing be a link, simply use the getUrl() function in a similar fashion:

<a href="<?php echo $category->getUrl()?>">
	<?php echo $category->getName()?>
</a>

Enjoy everyone!
Devin R. Olsen

47 Responses to “Magento Custom Category Listing Block”

  1. Magento webshop says:

    Heya i am for the primary time here. I came across this board and I in finding It really useful & it helped me out a lot. I am hoping to provide one thing back and help others like you helped me.

  2. Dakshika says:

    hi i want to sort by admin backend order..? how to add that feature into this code.. :(((

  3. Kirill Morozov says:

    Hey dude!
    Your solution created extra call for each category,
    That’s definitely not good.
    It would be better to use complex query to get all data you need at once.

    This is one of the reasons why people keep saying that Magento is slow.

  4. Magento建站 says:

    I found the similar solution from:
    http://stackoverflow.com/questions/1820012/magento-display-sub-category-list

    this also get category url and image.

    thanks for your share!

  5. JP says:

    Why did you not provide which files need to be edited in order to list the categories… I’m really starting to hate Magento. The file infrastructure is a mess!

  6. saurabh says:

    Really Appreciate all your information !!

  7. saurabh says:

    Thanks !! Thanks a lot for providing such stuff..!! Its really helpful for me.

  8. naemihail says:

    great tutorial!

    thank you so much for this.

  9. Spawn says:

    I’d like to add a few tricks on adding the links for the Categories and Sub Categories.

    just replace:

    echo $category->getName();

    with

    echo ‘getCategoryUrl($category).’”>’.$category->getName().”\n\n”;

    and for the sub category:

    echo $subCategory->getName();

    replace it with

    echo ‘getCategoryUrl($subCategory).’”>’.$subCategory->getName().”\n\n”;

    That did the trick for me in magento 1.5.1.0

    Hope that helps. :)

    Cheers

  10. Serks says:

    Would it be possible to leave a specific category out of the list?

    thanks

  11. Serks says:

    and to use thumbnail image (Magento 1.5)…

    <img src="getUrl(‘media/catalog/category/’) ?>getThumbnail()?>” />

  12. Serks says:

    Devin, as its been said a hundred times….great tutorial!

    If anyone wants to include the category images, here’s how i managed to do it…

    <img src="getUrl(‘media/catalog/category/’) ?>getImage()?>” />

    hope this helps someone

  13. Josh says:

    Thank you so much for this. You really saved me on a last minute request.

  14. Pablo Willian says:

    Great! Thank you very much =D

  15. hamza khan says:

    thank you so much for this explanation.
    please upload more and more nice explantion.
    keep it up

  16. Andy says:

    Hey Devin,

    great post there i altered mine slightly to turn it into a ‘brand quick find’ within a select dropdown.

    But one thing i’m having an issue with is the output isn’t ordering in the way it is in my categories.

    Do you get this problem to?

    Andy.

  17. Hiyas says:

    Thanks for posting this tutorial! Like the previous readers, I’m also curious how I could sort my categories. Right now my categories are listed by category ID. Is there a way this category listing can follow the order of my categories as I arrange them in the Magento admin panel? It would also be nice if we could highlight which category is currently active :)
    In any case, this tutorial has been very helpful. Thanks again!

  18. Mike says:

    Thanks much, really helpful. One question though. I’ve got a very small product catalog and would like to use this method to retrieve the complete category lists with products. This is a lot neater than other methods I’ve seen. Any ideas how I could get the product list for the subcategories?

  19. Eduardo says:

    Hi, I was looking for something as clear as this video tutorial. U really helped me understand much better Magento…
    I had spent too many hours trying to figure it out,
    awesome!

  20. luc says:

    Did anybody find a magento extension that could list products or categories like this http://www.vitacost.com/Brands? A-Z listing

  21. siva says:

    great how long i have been taking to find this one ……thanks

  22. Joe Fletcher says:

    For an example of how to sort this alphabetically, check out this post:

    http://stackoverflow.com/questions/4273898/how-to-sort-a-category-list-array-alphabetically-in-magento

  23. Mike says:

    Devin,

    Thanks for the tutorial. This has been a helpful example.

    Is there a way to alphabetize the categories? If so, can you please share that with us? It would make this addition much more sustainable for the long term.

    Thanks!

    Mike

  24. jayR says:

    i was hoping you can tell me how to sort the list in alphabet order :) Great code but to make it perfect we need sort-order

    Cheer :)

  25. jay says:

    Hi, how would I go about sorting by position in the admin panel? currently it is sorted by id

    Thanks

  26. Tim says:

    Devin, thanks for your time in getting this together.

    However, as I was working on a similar but slightly different block I noticed a function that eases the process a bit.

    After you have the default cat loaded (“…->load(2)”), instead of calling getChildren() to get the ids as a string, you can simply call getCollection(). This returns an array of models for you to loop through.

    You’re way works just fine, and I thank you again! This is just one less step, and also less overhead. However, we are dealing with Magento so it wouldnt be noticed anyay. Haha!

    Cheers,

    –Tim

  27. Luca says:

    Sorry, I made an error in copying the code. The correct one is:

    <a href="getUrl()?>”>
    getName()?>

    Thanks!

  28. Luca says:

    Hi Devin and thank you so much for the post!!

    Only one question. Where do I need to put the code below?

    <a href="getUrl()?>”>
    getName()?>

    Thank you so much!!!

  29. Michel says:

    Hello Devin!

    I put menu categories in top e subcategories in left.
    I need this:
    Clotes (Categories Top)
    sweaters(subCategories left)



    Acessories (Categories Top)
    rings (subCategories left)


    can you teach me please…
    I make this …

    load(2)->getChildren();
    $catIds = explode(‘,’,$cats);
    ?>

    load($catId);
    $subCats = Mage::getModel(‘catalog/category’)->load($category->getId())->getChildren();
    $subCatIds = explode(‘,’,$subCats);
    ?>

    2):?>

    load($subCat);
    ?>
    <a href="getUrl()?>”>
    getName()?>

  30. Mattia says:

    Have found: $this->isCategoryActive($category)

  31. Mattia says:

    And how to retrieve if the category is active? same to topnavigation..

  32. fes says:

    hmm, the echo’s are being stripped from the code but i think you guys can figure that one out yourselves :)

  33. fes says:

    Thanks for your code! I hope you don’t mind but i’ve created a recursive version with a dynamic root category:

    function renderChildren($category) {
    $children = Mage::getModel(‘catalog/category’)->load($category)->getChildren();
    if(!empty($children)) {
    $categories = explode(‘,’, $children);

    echo ”;
    foreach($categories as $categoryId) {
    $category = Mage::getModel(‘catalog/category’)->load($categoryId);
    echo ”;
    echo ‘getUrl() .’”>’. $category->getName() .’‘;
    renderChildren($categoryId);
    echo ”;
    }
    echo ”;
    }
    }

    renderChildren(Mage::app()->getStore()->getRootCategoryId());

    This way you can use it with multiple root categories and an infinite depth.

  34. Otto Tarella says:

    Good blog, keep me personally from searching it, I’m really interested to learn much more about it.

  35. @Marko Väljaots,
    Yeah I am well aware, but for some reason while building this tutorial I found it not working with me unless the condition was greater than 1 vs. the logical greater than 0.

    If someone could please confirm for me that their results come out clean with the logical greater than 0 condition that would be helpful.

  36. Marko Väljaots says:

    And thanks for the great article!

  37. Marko Väljaots says:

    There is a small mistake on line 17. subCatIds should be greater than 0, not greater than 1.

    For example:

    0):?>

  38. Kamwing says:

    非常感谢!THX

  39. Sven Aarts says:

    Thanks for this tutorial! I appreciate your work.

  40. Ingwa says:

    Devin, thanks so much! This code was really helpful to figure out Magento’s theming structure and layout files. The thing that I was running around in circles with was due to the fact that when I created my theme, from scratch mind you, I had defined the Templates and Skin directives under System > Config > Design > Themes but had not done the same for translations, layout or default. It’s imperative that these are all set to the theme name otherwise it’s an endless loop of not seeing changes. You’ve saved me my sanity. Thanks.

  41. Nellie says:

    This didn’t work for me. Is this for 1.4 only?

  42. Bart says:

    Devin, nevermind, I found an extension that does the job perfectly. Thanks anyway!

  43. Bart says:

    Hi Devin, thank you so much for your explanation about this. Really helped me. Question: Is there a way to only load the subcategories of the category you are in at that moment?
    So i have category A, with subs A1 and A2. If i’m IN category A, i only want to show subs A1 and A2 and not the other main categories (B, C, D etc.). Or does this require major modifications to the php?

  44. Thanks paul! This has promptly been corrected!

  45. paul says:

    Hello,

    You made a typo in the block reference..

  46. Mizpah says:

    A huge help, especially hearing the commentary as you built the file up, rather than simply reading the end result!

    Looking forwards to more of this quality :)

  47. I always enjoy feedback from my readers.

Leave a Reply