2

I want all parent category name using category Id

  • Main Category

    • Sub Category 1

      • Sub Category 3
      • Sub Category 4
    • Sub Category 2

      • Sub Category 5
      • Sub Category 6

Now I have id of this category Sub Category 6 Now i want all parent category name means i want this two name Sub Category 2,Main Category in frontend How to get all parent category name

5
$category = Mage::getModel('catalog/category')->load($id);

$catnames = array();
foreach ($category->getParentCategories() as $parent) {
    $catnames[] = $parent->getName();
}
1
  • You should go for the solution @Marius proposed, loading entire objects is extremely heavy and adds seconds to load times – Mayers May 13 '15 at 12:44
7

Simplest way without loads in loops:

$category = Mage::getModel('catalog/category')->load($categoryId());
$names = array();
foreach ($category->getParentCategories() as $parent) {
    $names[] = $parent->getName();
}
//do what you need with `$names` array
0
0
<?php
    // get current path
    $path = $this->getCurrentCategory()->getPath();

    // explode path
    $ids = explode('/', $path);

    foreach($ids as $id) {

        $cat = Mage::getModel('catalog/category')->setStoreId(Mage::app()->getStore()->getId())->load($id);
        $catName = $cat->getName();

        echo $catName;

    }

?>
0

If you use the function getParentCategories() then it called the function

load() which is taken more load time. See:

$pathIds = array_reverse(explode(',', $category->getPathInStore()));
        $categories = Mage::getResourceModel('catalog/category_collection')
            ->setStore(Mage::app()->getStore())
            ->addAttributeToSelect('name')
            ->addAttributeToSelect('url_key')
            ->addFieldToFilter('entity_id', array('in' => $pathIds))
            ->addFieldToFilter('is_active', 1)
            ->load()
            ->getItems();

Then it will better to call Custom Category collection and doesnot use collection load function .

$category = Mage::getModel('catalog/category')->load($id);
 $catnames=array();
$pathIds = array_reverse(explode(',', $category->getPathInStore()));
$Categories = Mage::getResourceModel('catalog/category_collection')
            ->setStore(Mage::app()->getStore())
            ->addAttributeToSelect('name')
            ->addFieldToFilter('entity_id', array('in' => $pathIds))
            ->addFieldToFilter('is_active', 1);


foreach ($Categories as $Eachparent) {
    $catnames[] = $Eachparent>getName();
}

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.