user2716061
user2716061

Reputation: 25

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.

Upvotes: 1

Views: 2380

Answers (2)

Tim Vroom
Tim Vroom

Reputation: 116

Instead of using a foreach to walk one time through the array you can use array_pop. Anyhow the function getCategoryIds() will return an array of all categories the product is in. This also include parent categories and are in logical order. The category with the lowest id will show up first.

Perhaps something like this will work for you:

<?php $_category_id = array_pop($_product->getCategoryIds()); ?>
<span>In </span>
<?php $_category = Mage::getModel('catalog/category')->load($_category_id) ?> 
<a  class="in-category" href="<?php echo $_category->getUrl() ?>">
    <?php echo   $_category->getName() ?>
</a>

Upvotes: 0

Marius
Marius

Reputation: 15216

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;?>

Upvotes: 4

Related Questions