Currently in a Category view page, its sub categories are displayed in a list format. I would like to change the list to select option so when there are too many sub categories users does not have to scroll all the way to the bottom to view the content.

Current Code:

<?php foreach ($this->getCurrentCategory()->getChildrenCategories() as $_subcat): ?>
    <li><a href="<?php echo $_subcat->getUrl() ?>"><?php echo Mage::helper('catalog/output')->categoryAttribute($_subcat, $_subcat->getName(), 'name') ?></a></li>
<?php endforeach ?>

How can I accomplish this so the sub-categories is displayed in a select option?


Just replace that code with...

<?php if($this->getCurrentCategory()->getChildrenCount() > 0) { ?>
    <select onchange="document.location = this.options[this.selectedIndex].getAttribute('rel')">
    <?php foreach ($this->getCurrentCategory()->getChildrenCategories() as $_subcat): ?>
        <option rel="<?php echo $_subcat->getUrl(); ?>"><?php echo Mage::helper('catalog/output')->categoryAttribute($_subcat, $_subcat->getName(), 'name'); ?></option>
    <?php endforeach ?>
<?php } ?>

This will create a drop-down select box of the exact same categories that would have been displayed with the existing code, it will also navigate the user to the category when they click on a selection.

EDIT: This is now TESTED AND WORKING code.

| improve this answer | |
  • @kane-show Your solution does works but the empty select option appears on category page that does not have any sub category. There must be a way to check if the category has active sub category and display accordingly using if statement? Very new to magento – DNA Mar 16 '15 at 6:18
  • Try this, I haven't tested it but let me know and I'll update my answer if it works. At the beginning add <?php if($this->getCurrentCategory()->getChildrenCategories()) { ?> and at the end add <?php } ?> – Kane Shaw Mar 16 '15 at 6:59
  • I don't think that comment will work. Try my updated answer. – Kane Shaw Mar 16 '15 at 7:06
  • @DNA I've just TESTED the code and updated my answer for the final time. USE THE UPDATED CODE, otherwise selecting options in the list wouldn't actually do anything. – Kane Shaw Mar 16 '15 at 7:26

This might help you.

<select id="category" class="myinput-text required-entry widthinput" name="category">
  $parentid=5; // parent id which you want sub category
  foreach($categories as $cat){
<option value="<?php echo $category->getId();?>"><?php echo $category->getName();?></option>
<?php } ?>
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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