Creating a sub-category left menu in Magento (that behaves itself)

April 20, 2010 by Adam · Leave a Comment 

I just had to do this, and couldn’t find any code anywhere that did it, and due to the lack of documentation with Magento it wasn’t fun to put together, so this may help someone:

<div class="leftnav-container">
<?php
if (!Mage::registry('current_category')) return;
$_categories = $this->getCurrentChildCategories();
$_count = is_array($_categories) ? count($_categories) : $_categories->count();
$_current = Mage::registry('current_category');
$_parent_id = $_current->parent_id;
$_parent_level = $_current->getLevel() - 1;
if($_count): ?>
	<ol>
	<?php foreach ($_categories as $_category): ?>
		<?php if($_category->getIsActive()): ?>
		<li>
			<a href="<?php echo $this->getCategoryUrl($_category) ?>"<?php if ($this->isCategoryActive($_category)): ?> class="current"<?php endif; ?>><?php echo $this->htmlEscape($_category->getName()) ?></a>
		</li>
		<?php endif; ?>
	<?php endforeach ?>
	</ol>
<?php elseif($_parent_level > 1): ?>
	<?php $_categories = Mage::getModel('catalog/category')->load($_parent_id)->getChildren(); $_categories = explode(',' ,$_categories); ?>
	<ol>
	<?php foreach ($_categories as $_category): $_category = Mage::getModel('catalog/category')->load($_category); ?>
		<?php if($_category->getIsActive()): ?>
		<li>
			<a href="<?php echo $this->getCategoryUrl($_category) ?>"<?php if ($this->isCategoryActive($_category)): ?> class="current"<?php endif; ?>><?php echo $this->htmlEscape($_category->getName()) ?></a>
		</li>
		<?php endif; ?>
	<?php endforeach; ?>
	</ol>
<?php endif; ?>
</div>