Q:

Get Subcategory in Magento

I need help. I use this code to get the category link under products info on a few pages in Magento:
<?php $categories = $_product->getCategoryIds(); ?>
<span>In </span>
<?php $i=1; foreach($categories as $k => $_category_id): ?>
<?php if($i>1) {break;} ?>
<?php $_category = Mage::getModel('catalog/category')->load($_category_id) ?> 
                <a  class="in-category" href="<?php echo $_category->getUrl() ?>"><?php echo $_category->getName() ?></a>
<?php $i++; endforeach; ?>

You can see it here: http://192.241.178.130/new_arrivals
Problem I'm having is that I want the script to display the category closest to the product but it's instead displaying the root category (Default category of the site)
M
Thanks.

A:

Try something like this:
<?php
$categoryIds = $_product->getCategoryIds();
$categories = Mage::getModel('catalog/category')
    ->addAttributeToSelect('url_key')//add url key to select
    ->addAttributeToSelect('name')//add name to select
    ->getCollection() //get categories as collection
    ->addAttributeToFilter('entity_id', $categoryIds)//filter only by selected ids
    ->addAttributeToFilter('is_active', 1)//get only active categories
    ->addAttributeToFilter('level', array('gte'=>2))//ignore root category and 'root of roots'
    ->setOrder('level', 'desc');//sort by level descending
$mainCategory = $categories->getFirstItem();//get only the category lowest in the tree
if ($mainCategory->getId()) : ?>
    <a  class="in-category" href="<?php echo $mainCategory->getUrl() ?>"><?php echo $mainCategory->getName() ?></a>
<?php endif;?>

