Question

For example I have a product called Nike shoes and it has categories Catalog > Shoes > Men.

What I need is just to get the name of the last category (Men). At first glance it can be retrieved very easily:

$cat = $_product->getCategoryIds();
$name= Mage::getModel('catalog/category')->load( end($cat) )->getName();

But there is a big problem, function getCategoryIds() return array of category ID's sorted numerically - so if last category (e.g. Men) has smaller index then previous one (e.g. Shoes) - I'll get incorrect result (Shoes).

Question: how to get list of category ID's sorted in the same way as on "Manage Categories" page? Or just how to get the last category?

Thank you

Was it helpful?

Solution

I hope someone comes up with a better solution, because I'm pretty sure mine if far from being perfect, sub-optimal, and VERY hacky. Anyway, when I need the most specific category related to a product, I do something like this:

$categoryIds = $product->getCategoryIds();
$collection = Mage::getModel('catalog/category')->getCollection()
        ->addAttributeToSelect('name')
        ->addAttributeToFilter('entity_id', $categoryIds)
        ->addAttributeToFilter('is_active', 1);
$collection->getSelect()->order('level DESC')->limit(1);

$name = $collection->getFirstItem()->getName();

By sorting the categories by their level, you will get the most specific one by calling getFirstItem(). Hopefully there's a better/easier way to do it which I'm not aware of, but this one works for sure.

I should note that, in case you have 2+ categories which are on the same level, you will get only one of them, specifically the first one which appears in the collection. The result is not so easy to predict, but it was usually good enough for what I needed to do.

Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top