Recently, I just finished coding out a website for a client in Magento. You can view the site at www.3graces.com, it was a full switch from some old legacy asp shopping cart to Magento. Im really happy with the way things turned out and the client is too, Magento just has so many wonderful features built-in.

One feature that I found wasn’t built in was a way to display each sub-category with an image, and its name on a landing page. Magento has a nice feature which allows you to assign an image to a category, but doesnt give you a way to make that show up in a listing somewhere.

I setup 6 main categories, with each having multiple sub-categories and I wanted to have a way to show all those sub-categories to the user on a nice page that was pleasing to the eye. Here is an example: Payot Paris by Category.

To achieve this layout, I created a block called sub_navigation.html and placed it in the following directory: app/design/frontend/3graces/default/template/catalog/navigaton/sub_navigation.html

<div id="categories">
<div class="col_full">
 
 
<div class="listing" >
<?php $_maincategorylisting=$this->getCurrentCategory()?>                        
<?php $_categories=$this->getCurrentChildCategories()?>
 
<?php if($_categories->count()):?>
           <? foreach ($_categories as $_category):?>
 
                        <? if($_category->getIsActive()):
 
                        $cur_category=Mage::getModel('catalog/category')->load($_category->getId());
           $layer = Mage::getSingleton('catalog/layer');
           $layer->setCurrentCategory($cur_category);
 
			$catName = $this->getCurrentCategory()->getName();  
 
			if($_imageUrl=!$this->getCurrentCategory()->getImageUrl()):?>
 
			<div class="category-box">
				<div class="category-image-box">
					<a href="<?php echo $this->getCategoryUrl($_category)?>"><img src="/skin/frontend/3graces/default/images/category_image_default.gif"></a>
				</div>
				<div class="category-name">	
					<p><a href="<?php echo $this->getCategoryUrl($_category)?>">
						<?php echo $catName ?></a></p>
				</div>
			</div>	
 
			<?endif?>
 
			<? if($_imageUrl=$this->getCurrentCategory()->getImageUrl()):?>
 
         <div class="category-box">
				<div class="category-image-box">
					 <a href="<?php echo $this->getCategoryUrl($_category)?>"><img src="<?php echo $_imageUrl?>" height="80"></a>
				</div>
				<div class="category-name">	
					<p><a href="<?php echo $this->getCategoryUrl($_category)?>"> <?php echo $_category->getName()?></a></p>
				</div>
			</div>
 
 
 
<?                                              
                        endif;
                        endif;?>
            <?endforeach?>
 
            <?php /* This resets the category back to the original pages category
****     If this is not done, subsequent calls on the same page will use the last category
****    in the foreach loop
*/   ?>
<?php $layer->setCurrentCategory($_maincategorylisting);  ?> 
    <?endif;?>
 
 
</div>
<br clear=all>
</div>
</div>

If you notice, I placed an if statement in the code that first checks if an image has been set for the category. If one has, it will show it – if there isn’t an image it will show a default image that I have chosen. Here is an example, when only 1 image for a category has been setup, and the rest are the default.

To make the block show up as an option in Magento Admin, you will need to go to CMS > Static Blocks. Once you get there, click Add New Block and fill in the following fields.

Block Title: Sub Category Listing
Identifier: sub_category_listing
Status: Enabled
Content: {{block type=”catalog/navigation” template=”catalog/navigation/sub_category_listing.phtml”}}

Once you have added all those fields, you can click save. Now to enable this static block for a parent category that contains a bunch of sub-categories with images that are set.
Go to: Catalog > Manage Categories

Then click on the parent category to which you wish to add this layout, scroll to the bottom of the first tab “General Information”.

You will see the following fields, just setup as follows:

Display Mode: Static Block Only
CMS Block: Sub Category Listing
Is Anchor: Yes

Now if you go back to your category on the website, you should see your newly setup sub category image listing page. If you arent seeing any images, make sure you setup you default image and placed it in the current directory within your magento install.

Thanks!

This website uses IntenseDebate comments, but they are not currently loaded because either your browser doesn't support JavaScript, or they didn't load fast enough.

78 Responses to “Magento: Custom Category Images Listing Block Tutorial”

78 Comments so far
  1. There is a bit of a inconsistency between filenames used above, sub_navigation.html should be sub_category_listing.phtml

    Regards
    Tim Pearson

  2. Very nice work you did there!!

  3. Thanks for the post, a great help.

    One suggested modification on line 24. use the getSkinUrl() instead of the hard coded path.

    <img src=”getSkinUrl() ?>images/category_image_default.gif” alt=”[Image] No image available”>

  4. I spent quite a bit of time searching the Magento Site for something even remotly similar with very little luck. This is perfect and exactly what (should be built into Magento) I need!

    Thank you so much!!

  5. Fantastic – I echo Chris’ comments above – this is just one of those things that Magento is missing. I hit a snag with coding the Static Block as I had installed the Fontis WYSIWYG – this would not add the code properly for the static block – thankfully it can be just as easily uninstalled using the Magento Connect manager.
    Thank you – first class work

  6. Excellent tutorial, thank you for sharing your knowledge
    Cheers,
    Alex

  7. By far the best tutorial I’ve read regarding tips for Magento. I agree this should have been added by default to the Magento core. Thanks Jake!

    David

  8. Thanks a lot…!!! works like a charm :-)

  9. Excellent!! Thxs a lot!

  10. Awesome Tutorial! Works great! Only creation:

    {{block type=”catalog/navigation” template=”catalog/navigation/sub_category_listing.phtml”}} should be changed to

    {{block type=”catalog/navigation” template=”catalog/navigation/sub_navigation”}}

  11. How do you get the categories to to be displayed horizontally?

  12. Tried your tutorial, but i can’t get it to work. Were i expect the block to be there is a blank space. Any ideas? My site is based on the blue theme, and the pages are 3 columns.

  13. I would also like to mention that 3graces is an awesome magento site, very well done

  14. Well played, sir. I was trying to figure out the best way to do this, and you have provided a nice, succinct solution here. Thanks again!

  15. i got it to work! yes…
    It was to do with the inconsistency between filenames used above, sub_navigation.html should be sub_category_listing.phtml

    I’m a dumbass. Anyway once you get subcategory images working how do you only list products and not show the image?

  16. Awesome Tutorial! ONE of the BEST I’ve seen.I MUST be really stupid because i still can’t get it to work. when i go to the category there isn’t any images there.When i click on one of it’s subcategories i see a 10X size category image!! PLEASE HELP someone PLEASE

  17. i received an error while using this code
    Parse error:on line 46

  18. I get a parse error on line 9, I’m using the newest upgrade to magento

  19. Lol nevermind, dumb mistake. When you copy his code, make sure its exactly how you see it, because i copied plain text with all the ’s in it. Got it working! Thank you!

  20. exactly what i been looking for.
    thanks for the great post.

  21. Help ?? i get the following error ?

    Fatal error: Call to a member function count() on a non-object in /homepages/34/d239231162/htdocs/magento/app/design/frontend/default/blank/template/catalog/navigation/sub_category_listing.phtml on line 9

    Running magento v.1.3 using the blank template they provide.

  22. Any chance you can provide the file as downloadable, so there are no cut and paste issues. Which this may be after reading Brians note above about “because i copied plain text with all the ’s in it.” not sure what he means about ’s ???

    kinda desperate to get this working if you hadn’t guessed already :o)

    Thanks
    Mark

  23. but i get Parse error

  24. I’ve been trying to achieve a similar affect, but with product pages. I sell configurable items, and each one has different sets of fabrics. I’ve been trying to figure out a way of creating different static blocks that is a grid view of the fabrics so that the customers can see them, and assign them to the correct product.
    Unfortunately, can’t seem to get past how to show a dynamic static block on a product detail page.

  25. How can I display the categories horizontol?

    THX

    Alex

  26. if u get a Parse Error: syntax error, unexpected $end

    this is often caused by the use of Short Open tags in PHP
    try to change all <? to <?php

    or allow short open tags in your PHP.INI file. Look for the SHORT_OPEN_TAG directive in your PHP.INI file and set it to “1″

  27. Unfortunately this didn’t work either :o( Same error.
    Fatal error: Call to a member function count() on a non-object in

    Thanks for your reply.
    A very frustrated mark.

  28. try this code for sub_category_listing.phtml
    also read te above reply from me if u get the syntax error after using this code.

    getCurrentCategory();
    $id = $category->getId();
    ?>

    getCurrentChildCategories(); ?>

    getIsActive()): ?>

    <a href=”getURL() ?>” title=”htmlEscape($_category->getName()) ?>”>

    <img src=”getImageUrl() ?>” width=”140″ alt=”htmlEscape($_category->getName()) ?>” />

    ” */ ?>

    <h3<a href=”getURL() ?>” title=”htmlEscape($_category->getName()) ?>”>htmlEscape($_category->getName()) ?></h3

    getDescription() ?>

  29. im forgot something,

    if ur using this script and magento 1.3 and ur images are not showing.
    u have to do the following also:

    go to \magento\app\code\Mage\Catalog\Model\Resource\Eav\Mysql4\Category.php

    search for: $collection = $category->getCollection();

    and add this: ->addAttributeToSelect(‘image’)

    u will get shomething as:

    $collection = $category->getCollection();
    /* @var $collection Mage_Catalog_Model_Resource_Eav_Mysql4_Category_Collection */
    $collection->addAttributeToSelect(‘url_key’)
    ->addAttributeToSelect(‘name’)
    ->addAttributeToSelect(‘image’)
    ->addAttributeToSelect(‘all_children’)
    ->addAttributeToSelect(‘is_anchor’)
    ->addAttributeToFilter(‘is_active’, 1)
    ->addIdFilter($category->getChildren())
    ->setOrder(‘position’, ‘ASC’)
    ->joinUrlRewrite()
    ->load();
    return $collection;
    }

  30. Thanks for your help stephan,

    I don’t think this is destined to happen for me! No Parse Error but now nothing showing and when I view source it’s as if it isn’t even trying to load sub_category_listing.phtml

    I have a default image and images for sub categories, but they still don’t display. Just shows the title of the main category your on.
    I wish someone would write an extension for this, that I could just install and it would work :o)

    Thanks
    Mark

  31. hi mark,
    Its not working because this website scrambled up the php code.
    im gonna upload the file for u so u have the right php code

    u can download the subcategory listing file from:

    http://www.megafileupload.com/en/file/100989/SCL-zip.html

    hope this will work for u.

    and don’t forget to add: ->addAttributeToSelect(’image’)

    to the category.php file

  32. FANTASTIC!!! Now we are rocking! THANK YOU. All works except the images i’ve added for the sub categories don’t display :o( They are added in the admin and display in the admin. When I view the source it’s writing out the following:

    Small

    ALT text is appearing and the links are working… but it’s not writing out the image paths for some reason. If I view one of the sub categories then it’s image displays with the products below, so the sub category images are definitely there.

    Can you help me out again? I owe you big style :o)

    Thanks massively again for you help!
    Mark

  33. Ooohps… this is the source:

    Small

  34. If you click the word small in previous posts, it takes you through to the site.
    <img src=”" width=”140″ alt=”Small” />

  35. mark,

    go to \magento\app\code\Mage\Catalog\Model\Resource\Eav\Mysql4\Category.php

    search for:
    $collection = $category->getCollection();

    and add this:
    ->addAttributeToSelect(’image’)

    u will get shomething as this:

    $collection = $category->getCollection();

    $collection->addAttributeToSelect(’url_key’)
    ->addAttributeToSelect(’name’)
    ->addAttributeToSelect(’image’)
    ->addAttributeToSelect(’all_children’)
    ->addAttributeToSelect(’is_anchor’)
    ->addAttributeToFilter(’is_active’, 1)
    ->addIdFilter($category->getChildren())
    ->setOrder(’position’, ‘ASC’)
    ->joinUrlRewrite()
    ->load();
    return $collection;
    }

  36. I posted question to magento with no luck:
    ————————————————-
    I need to show sub-categories of certain category from cms page. Is it possible?

    suppose i have category id 32 and it has sub-categories. I need to show sub-categories of id 32.

    is there something like?
    {{block type=”catalog/navigation” name=”catalog.category” template=”catalog/category/example.phtml” category id=32}}
    —————————

  37. Hi Stephan,

    That was already added and it still just displayed empty image tags, with no images displayed :o( It’s just not getting the image paths? This is driving me mad now!

    Thanks
    Mark

  38. hi mark,

    i dont know whats wrong,
    i think the problem is within ur category.php file

    here u can download the working category.php file

    http://www.megafileupload.com/en/file/102917/magentocategoryfile-zip.html

    u have to save this php file to:

    \magento\app\code\core\Mage\Catalog\Model\Resource\Eav\Mysql4\Category.php

    and dont forget to refresh ur cache in magento admin

    Hope this works for u.

  39. Hi,

    I just wanted to thank you for this awesome tutorial! This is exactly what I needed for my store and you read my mind :)

    It’s a shame that the magento core developers did not implement this by default because I’m sure that lots of shops require this functionality!

    Anyway, thank you very much

    Keep up the good work
    Chris

  40. Hi Stephan,

    Thanks for all your help! Added your file and cleared cache, it is still generating blank image tags :o(

    Thanks
    Mark

  41. mark,
    what version of magento ur using?
    if ur using an older version, update then to 1.3.1
    and install this files again.
    with this version it has to work.

  42. having issues with this tut i keep getting an error on line 0-all the way through copied exactly even went through and changed link from his theme but nothing some get a change link the file that does work for sure i have version 1.3.1

  43. Hi stephan ,i have read this tute and applied it but I think this file(sub_category_listing.phtml) is not cosidered at all as when i put die(); in it nothing happend .Is there any requiremnet to specify file name in catalog.xml or somewhere else

  44. Magento ver is 1.1.8. can anybody help?

  45. Hi Stephan,

    Thank you VERY much for all your help, i still can’t get this to work and have wasted too much time on such a simple thing. I am reverting back to using zencart which does this with ease :o) Need to do this as the clients site is starting to get behind schedule.

    Thanks again Mark

  46. Hi Mrak You can try this for displaying images

    here $catid is the id of the category for which you want to show image.

    $_category = Mage::getModel(‘catalog/category’)->load($catid) ;
    $_imgHtml = ”;

    if ($_imageUrl = $_category->getImageUrl()) {
    $_imgHtml = ‘htmlEscape($_category->getName()).’” />’;
    $_imgHtml = $_helper->categoryAttribute($_category, $_imgHtml, ‘image’);
    }
    if($_imgHtml){

    $o .= ‘getId().’” href=”‘.$base_url.$category->getUrlKey().’”>’.$_imgHtml.’‘.$desc;
    }

  47. Sorry instead of these lines

    if($_imgHtml){

    $o .= ‘getId().’” href=”‘.$base_url.$category->getUrlKey().’”>’.$_imgHtml.’‘.$desc;
    }

    try these line

    if($_imgHtml){

    $o .= ‘getUrlKey().’”>’.$_imgHtml.’‘;
    }
    echo $o;

  48. or just echo $_imgHtml ;

  49. DeadlyPorpoise

    May 28th, 2009 at 7:00 pm

    Hi Chhaya,

    Did you ever solve the fact that sub_category_listing.phtml is never referenced?

    I have the same issue using Magento 1.3.1

  50. Is it possible to recap this discussion?

    As Magento moves along, some of this has changed, it would be nice to have a concise set of instructions and code examples for 1.3.2.

    It’s a great feature and I’m sure lots of folks would use it if it was a little less confusing to deploy and worked as it does on the reference site. The main challenges I have seen are:

    1) Categories present in a list format vs grid format.
    2) Category images are not used, only default images come up.

  51. Hi ,
    yes i also faced the same problem you try this ,here $catid is the category id
    $_category = Mage::getModel(’catalog/category’)->load($catid) ;
    $_imgHtml = ”;

    if ($_imageUrl = $_category->getImageUrl()) {
    $_imgHtml = ‘htmlEscape($_category->getName()).’” />’;
    $_imgHtml = $_helper->categoryAttribute($_category, $_imgHtml, ‘image’);
    }
    if($_imgHtml){

    echo $_imgHtml;
    }

  52. I have tried everything said on this website to get this to work and when i click on my main category it just comes up with a blank page like i have no items. i have even downloaded the phtml file listed on this page but still doesn't show pictures of my catagories just an empty page. please help.

  53. Awesome Tutorial! Works great!…You are a genius Stephan.
    How do you get the categories to be displayed horizontally?

  54. I can't get this to work with 1.3.2.1. Anybody managed to do this?

  55. Sorry, had wysiwyg editor activated which inserted a whole lot of unneeded tags., It is working like a charm actually!

    The two things I am trying to figure out now are: how can I make layered navigation work if I set category display to static block only? Is this possible at all?
    And another thing: why are there spaces between the category pictures on some landing pages if I set the display to block? (Like here: http://3graces.com/brands/perlier/categories/ ) I am having the same problem on one of mine.

    Besides that, very nice work man, thank you! And the sites looking very good too btw!

  56. I cant get this to work with 1.3.2.3. Any ideas? I just get a blank page?

  57. Hi there, for all of you having issues with this I just figured out that when you copy the {{ block code the " (quotations) need to be typed over with quotes from your keyboard. I guess it was copying a different quote type. I wasted hours trying all kinds of different things and the second I changed that it worked like a snap.

  58. I got this to work with 1.3.2.3. This may not apply to others, but with my install the quotes for the block tag were being changed when stored (some were delimited with slashes ", others were formatted like “ as opposed to "), which meant they weren't properly parsed later. I added the following to the top of the /index.php file..

    function stripslashes_deep($value) {
    $value = is_array($value) ? array_map("stripslashes_deep", $value) : stripslashes($value);
    return $value;
    }
    $_POST = array_map("stripslashes_deep", $_POST);

    Then I went back to the page to edit the static block and changed the block tags quotes to normal double quotes, and it worked. Mind you, the sub_category_listing.phtml file I downloaded originally had a PHP error, but it's easily fixed.

  59. Some code has to have changed in 1.3.2.1.. I have the latest version 1.3.2.3 and I have the same issues.. Blank screen… Also may have something to do with template…

    Anyway, I am going to search more however this is the best link I found so far.. Thank you!

  60. If you have trouble getting the static block to show, it could be because you are using the wrong type of quote marks (") in the admin. I copy and pasted straight from here and after a lot of head scratching noticed my quote marks were not quite right. Random I know…
    Great piece of code though, thank you very much.

  61. remember to change favicon :)

  62. I got it, the " in the block where wrong, cant see the difference lol.

    {{block type="catalog/navigation" template="catalog/navigation/sub_category_listing.phtml"}}

    Just redo all the "

    Only the image isnt showing atm.

  63. Hmm i'm useing 1.3.2.2 and it's not working for me.
    The images are the problem, they are blank.

    http://www.magentocommerce.com/boards/viewthread/...

    Does anyone knows what to change into the <img> code?

  64. If u get <img src="" > , the empty image:

    just make sure in the admin part u upload an image with the category products. I was struggling for hours on that and didn't notice u had to upload an image ;x

  65. This is by far the best tutorial out there when it comes to Magento. You Rule!

  66. Hi I'm new to magento and although I got the tutorial working, I wonder if anyone cane help me with adding the description text. I tried <?php echo $this->htmlEscape($_category->getDescription()) ?> but nothing seems to happen.

  67. Hey, I really dig what you did with the site, http://www.3graces.com. Looks great. I'm looking to utilize what you have for your featured products slider. Is that a jquery slider? If you can point me in the direction on where I can find that code, the library I need that would be great.

    Thanks,
    Mike

  68. Hey there. I"m new to magento, and i just want to create a static block that displays all of the top level categories (sub cats aren't too important, can add code for that in if need be). I've tried following a number of tutorials, but no luck. Any hints/tips?

  69. Okay everyone, if you don't have sohort tags enabled, it won't work.

    replace all the <? tags with <?php

    It'll work then.

    Did anyone solve the horizontal issue yet ?

  70. How did u solve it, Mark? Im getting the same error!

    Help please! thx Max

  71. found the error. line 8 must be:

    <?php if(count($_categories)):?>

  72. Hello.
    Thought I should report that this worked fine for me on Magento 1.3.2.3 with no real difficulty. A few points that might be worth considering:
    1. When I copied the *.phtml code from the tutorial, I first cut and paste if to my text editor, which is TEXTWRANGLER (macintosh). This may have fixed the quotes issues experienced by other users. I suspect Jake may have updated his tutorial code in response to comments so this might not be a concern.
    2. I used FireBug (a Firefox extension that I highly recommend) to copy the *.css entries referred to in the *.phtml file from the 3graces.com website and used that as a basis for my syles. Before doing this the thumbnail images were arranged vertically. This is an essential step to format the output.
    Hope this is helpful
    P.S. My site(s) are up and running if you want to take a look or copy code:
    hautemama.ie and hautemamaboutique.com

  73. Thanks! That solved the problem!!

  74. Hi Robert,

    I'm having trouble locating which css entries to add/modify. Its working on my site, but in vertical rows – want to in 4 columns.

  75. Hi Pranil, I think I have something similar to what you were looking for here:

    http://www.creativereason.com/category-thumbnail-...

    Hope you solved your problem.

  76. I had this problem as well and realised that my installation wasn't using Category.php to load the sub category information. Turns out that I had flat catalogs turned on so the file you want to amend is:

    appcodelocalMageCatalogModelResourceEavMysql4CategoryFlat.php

    If this file doesn't exist then copy the one from

    appcodecoreMageCatalogModelResourceEavMysql4CategoryFlat.php

    and then find the _loadNodes function. This is where the sql for the extracting info from the flat category table is built and executed. In the _loadNodes find where the sql is built, which should look like this:

    $select = $_conn->select()
    ->from(array('main_table'=>$this->getMainStoreTable($storeId)), array('main_table.entity_id', 'main_table.name', 'main_table.path', 'main_table.is_active', 'main_table.is_anchor'))

    and add an extra field to select, in this case the "image" field by changing the line to look like this:

    select = $_conn->select()
    ->from(array('main_table'=>$this->getMainStoreTable($storeId)), array('main_table.entity_id', 'main_table.name', 'main_table.image', 'main_table.path', 'main_table.is_active', 'main_table.is_anchor'))

    Hope this helps.

    Thx for starting this post its has been of great help to me.

  77. Martin
    Below, please find the *.css code that I used. I don't specifically set it to 5 columns, but the images size and the available space make it that way. On slight glitch: if you have a category title that take up more than 1 row of text it will push the other categories off to one side.
    -rob

    <code>

    /* Category landing */

    .category-box {
    text-align: center;
    float:left;
    margin:0px 15px 15px 0px;
    width: 120px;

    }

    .category-image-box {
    /*
    background: url(../images/category_image_bg.gif) no-repeat;
    */
    height:175px;
    width: 120px;

    }

    .category-image-box img {
    margin: 5px 5px 0px 0px;
    border-width: 1px;
    border-color: #4b3425;
    border-style: solid;
    }

    .category-name a:link, .category-name a:visited {
    color: #7c2b87;
    font-weight: bold;
    font-size: 14px;
    text-decoration: none;
    line-height:16px;
    }

    .category-name a:hover, .category-name a:active {
    color: #4b3425;
    font-weight: bold;
    font-size: 14px;
    text-decoration: none;
    line-height:16px;
    }

    </code>

  78. Hi!
    Works perfect! But two questions:
    - i only want to list subcategories and not sub-subcategories.
    - i want the subcategories to be listed by 3 one one line (now there's only one on one line)




XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">

By submitting a comment here you grant Jake Rutter a perpetual license to reproduce your words and name/web site in attribution. Inappropriate comments will be removed at admin's discretion.