0

I am using the following code to list sub categories of main categories instead of products. It works great but I need to check if the category has an image. if it doesn't I want it to not show a broken image.

here is the code i'm using:

<?php
$_category  = $this->getCurrentCategory(); 
$collection = Mage::getModel('catalog/category')->getCategories($_category->entity_id);
$helper     = Mage::helper('catalog/category');
?>

<ul>
<?php foreach ($collection as $cat):?>
        <?php if($_category->getIsActive()):?>
            <?php 
                 $cur_category = Mage::getModel('catalog/category')->load($cat->getId());
                 $_img = $cur_category->getImageUrl();  
            ?>
            <li>
                <a href="<?php echo $helper->getCategoryUrl($cat);?>">
                     <img src="<?php echo $_img?>" title="<?php echo $cat->getName();?>"/>
                     <cite><?php echo $cat->getName();?></cite>
                </a>
            </li>
        <?php endif?>
<?php endforeach;?>

2 Answers 2

0

Try the below code,

Inside <li>,update the code as

         <li>
           <a href="<?php echo $helper->getCategoryUrl($cat);?>">
            <?php if($_img){?>                   
                <img src="<?php echo $_img?>" title="<?php echo $cat->getName();?>"/>
            <?php }?>
             <cite><?php echo $cat->getName();?></cite>
           </a>
         </li>
6
  • your code is throwing an error. Jul 8, 2015 at 20:01
  • what error you got? Jul 8, 2015 at 20:02
  • its echoing if($_img){ Jul 8, 2015 at 20:04
  • I have updated the answer. Missed the php tags Jul 8, 2015 at 20:05
  • It is the default code. For reference check the catalog/category/view.phtml Jul 8, 2015 at 20:07
0

You just have to check if $_img does not equal to null.

<?php foreach ($collection as $cat):?>
        <?php if($_category->getIsActive()):?>
            <?php 
                 $cur_category = Mage::getModel('catalog/category')->load($cat->getId());                  
            ?>
            <li>
                <a href="<?php echo $helper->getCategoryUrl($cat);?>">
                   <?php if($_img = $cur_category->getImageUrl()): ?>
                     <img src="<?php echo $_img?>" title="<?php echo $cat->getName();?>"/>
                   <?php endif; ?>
                     <cite><?php echo $cat->getName();?></cite>
                </a>
            </li>

        <?php endif; ?>
<?php endforeach;?>
2
  • This works but if the image isn't available it doesn't show anything. I would like for the category title to at least show. Jul 8, 2015 at 20:01
  • @user3262111 I updated my answer Jul 8, 2015 at 20:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.