shashank
shashank

Reputation: 566

How to get last level category of each product in magento

I am trying to get last level category name with its product count for each product on listing page. explained as below-

Category
                -> Sub-category 1
                          ->Sub-sub-category 11   -> Product 1
                          ->Sub-sub-category 12 
                              -> Sub-sub-sub-category 13  ->Product 2  
                -> Sub-category 2
                          ->Sub-sub-category 21 
                              -> Sub-sub-sub-category 22  ->Product 3 
                          ->Sub-sub-category 23   -> Product 4

I want to get only categories "Sub-sub-category 11", "Sub-sub-sub-category 13", "Sub-sub-sub-category 22" and "Sub-sub-category 23" which are the last level categories of Products 1, Products 2, Products 3, Products 4. I found below link get last level category name of a product in magento but it only gets third level category.

Upvotes: 2

Views: 2914

Answers (3)

OddBrew
OddBrew

Reputation: 498

A little late, but this can be accomplished very simply, use this function when you want to get the category of the deepest level for a given product :

public function getProductLastLevelCategory(Mage_Catalog_Model_Product $product)
{
    /** @var Mage_Catalog_Model_Resource_Category_Collection $categories */
    $categories = $product->getCategoryCollection()
        ->addAttributeToSelect('*')
        ->addOrder('level');

   return $categories->getFirstItem();
}

The base collection contains all the categories the given product belongs to, and the trick relies on sorting them by level (implicitly DESC).

Upvotes: 5

haris
haris

Reputation: 1

at my problem i try this code and success

<?php
$_helper = $this->helper('catalog/category');
$_storeCategories = $_helper->getStoreCategories();
?>

<?php
function getLastCategory($_categories)
{
    $_helper = Mage::helper('catalog/category');
    if (count($_categories) > 0) {
        foreach ($_categories as $_category) {
            $_category = Mage::getModel('catalog/category')->load($_category->getId());
            $_subcategories = $_category->getChildrenCategories();
            if (count($_subcategories) > 0) {
                getLastCategory($_subcategories);
            } else {
                echo($_category->getName()."<br />" );
            }
        }
    }
}

$lastCategory = getLastCategory($_storeCategories);
?>

Upvotes: 0

Sony
Sony

Reputation: 219

Hi you can use the method getChildrenCount() for your category and check if it's equal to 0

if($category->getChildrenCount() == 0) {
  // Do something
 }

Upvotes: 1

Related Questions