Jyotiranjan
Jyotiranjan

Reputation: 693

category tree in magento with more level on the frontend

thanks .............. but ...I have below code which is working up to 1st level not for more level in category tree could someone help me for the 3rd level and more........... level of the category tree...........that means if i I will click the parent category only that particular parent open with his children all other will on closed manner like Category1 -subcategory1 ----subsubcategory1 -subcategory2

Category2 -subcategory1 -subcategory2

      <?php
          $obj = new Mage_Catalog_Block_Navigation();
          $store_cats   = $obj->getStoreCategories();
          $current_cat  = $obj->getCurrentCategory();
           $current_cat = (is_object($current_cat) ? $current_cat->getName() : '');

            foreach ($store_cats as $cat) {
                  if ($cat->getName() == $current_cat) {
                        echo '<li class="current"><a href="'.$this->getCategoryUrl($cat).'">'.$cat->getName()."</a>\n<ul>\n";
                        foreach ($obj->getCurrentChildCategories() as $subcat) {
                        echo '<li><a href="'.$this->getCategoryUrl($subcat).'">'.$subcat->getName()."</a></li>\n";
                  }
                   echo "</ul>\n</li>\n";
                  } else {
                       echo '<li><a href="'.$this->getCategoryUrl($cat).'">'.$cat->getName()."</a></li>\n";
                       }
                 }
         ?>

Upvotes: 0

Views: 2177

Answers (1)

pzirkind
pzirkind

Reputation: 2338

The easiest way to solve this is to create a recursive function (a function that calls itself).

Here is how you might want to set up your code:

//go through all the parent catgeroies
foreach ($store_cats as $cat) {
        // if it's the category we are looking for let's spit it out as an <li>
        if ($cat->getName() == $current_cat) {
                    echo '<li class="current"><a href="'.$this->getCategoryUrl($cat).'">'.$cat->getName()."</a>\n<ul>\n";
                    // let's get all the subcategories no matter how deep (look at function below).
                    getChildCategories();

       }
}
//our new sub-category getter
public function getChildCategories() {

            // lets loop through all the children of the current category and spit out <li> for them    
            foreach ($obj->getCurrentChildCategories() as $subcat) {
                         echo '<li><a href="'.$this->getCategoryUrl($subcat).'">'.$subcat->getName()."</a></li>\n";

                        //lets call ourself again to see whether there are deeper layer to be found
                         getChildCategories();
              }
}

What you would want to add to your code is an if statement checking whether there are children:

   if ($obj->getCurrentChildCategories()) {//then loop through etc.}

This way you avoid hitting errors when you hit rock bottom.

Upvotes: 1

Related Questions