Magento 1.9 – How to Display Sub Categories as Images on Category Page

categoryhtmlmagento-1.9phtmlproduct

Im trying to display Sub categories as images on my Category page the page im talking about is here:

What i did at this point is i created a PHTML file with the following code:

<?php
$category = Mage::getSingleton('catalog/layer')->getCurrentCategory();
$categories = $category->getCollection()
        ->addAttributeToSelect(array('name', 'image'))
        ->addAttributeToFilter('is_active', 1)
        ->addIdFilter($category->getChildren())
?>
<div class="category-products">
  <ul class="subcategories products-grid columns4">
      <?php foreach ($categories as $category): ?>
          <li>
              <a href="<?php echo $category->getUrl() ?>"><img src="<?php echo Mage::getBaseUrl('media') . 'catalog' . DS . 'category' . DS . $category->getImageUrl() ?>" alt="<?php echo $this->htmlEscape($category->getName()) ?>" />
              <span><?php echo $category->getName() ?></span></a>
          </li>
      <?php endforeach; ?>
  </ul>
</div>

I created a static block with the following information:

Name: Subcategories
Code: subcategories
Status: Enabled
Content:

{{block type="core/template" template="catalog/category/sub.phtml"}}

So as you can see i have a few problems, one is that the images dont show up the link i get when i inspect it is

http://websiteurl.co.uk/media/catalog/category/http://websiteurl.co.uk/media/catalog/category/construct2_7.jpg

When it should actually be:

http://websiteurl.co.uk/media/catalog/category/construct2_7.jpg

The second problem i have is that every single page is showing the same 4 Categories no matter what page i go into. When i go into the category 'Floor Tile' It should show different subcategories but instead it shows the same 4 again.

I read somehwere that magento caches your current category and thats why the 4 categories dont change but even when i flush my cache it doesn't change.

Please Help!

Best Answer

Update your code with below code

    <?php
    $category = Mage::registry("current_category");
    if($category->getId()){
    $categories = $category->getCollection()
            ->addAttributeToSelect(array('name', 'image'))
            ->addAttributeToFilter('is_active', 1)
            ->addIdFilter($category->getChildren())
    ?>
    <div class="category-products">
      <ul class="subcategories products-grid columns4">
          <?php foreach ($categories as $category): ?>
              <li>
                  <a href="<?php echo $category->getUrl() ?>"><img src="<?php echo $category->getImageUrl() ?>" alt="<?php echo $this->htmlEscape($category->getName()) ?>" />
                  <span><?php echo $category->getName() ?></span></a>
              </li>
          <?php endforeach; ?>
      </ul>
    </div>
<?php } ?>
Related Topic