0

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 https://stackoverflow.com/questions/20926118/get-last-level-category-name-of-a-product-in-magento but it only gets third level category.

  • are you need on product listing page (category lading page)? – Abdul Jan 7 '16 at 9:46
  • @Abdul. yes I need it on listing page. – Shashank Kumrawat Jan 7 '16 at 9:49
1

Try bellow code on product listing block or list.phtml

public function currentCategory()    
{
    // Put here your current category id 
    $currentCategoryId = 3;
    $category =  Mage::getModel('catalog/category')->load($currentCategoryId);

    //OR $category = Mage::registry('current_category');

    $this->lastLevelCategory($category,2);
}
public function lastLevelCategory($category, $level=0)
{
    $html = '';
    $collection = Mage::getResourceModel('catalog/category_collection');
    $collection->addAttributeToSelect('url_key')
        ->addAttributeToSelect('name')
        ->addAttributeToSelect('all_children')
        ->addAttributeToFilter('is_active', 1);

    $collection->setLoadProductCount(true);
    $children = $collection->addIdFilter($category->getChildren());

    if ($children) {
        foreach ($children as $i => $child) {
            $this->lastLevelCategory($child, $level+1);
        }
        if(!$category->getChildren()) {
            $html .= "Category Name : ".$category->getName().'<br>';
            $html .= "Product Count : ".$category->getProductCount().'<br>';
        }
    }
    echo $html;
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.