Sajeev Rajan
Sajeev Rajan

Reputation: 144

How to get Category name in Magento?

I’m new to Magento. I have a 'select-box' that list all the main 'categories-name'. How to get 'Category-name' in Magento?

Upvotes: 4

Views: 23068

Answers (2)

Sajeev Rajan
Sajeev Rajan

Reputation: 144

<select>
<?php
$category = Mage::getModel('catalog/category');
$tree = $category->getTreeModel();
$tree->load();

$ids = $tree->getCollection()->getAllIds();

if ($ids)
{
     foreach ($ids as $id)
  {
     $cat = Mage::getModel('catalog/category');
     $cat->load($id);
     if($cat->getLevel()==1 && $cat->getIsActive()==1)
     {
        echo "<option>";
        echo $cat->getName();
        echo "</option>";
     }
  }
} 
?>
</select>

Upvotes: 7

enenen
enenen

Reputation: 1967

Firstly get Catalog->Category helper:

$helper = Mage::helper('catalog/category');

Location: app/code/core/Mage/Catalog/Helper/Category.php

Then:

<select>
<?php foreach ($helper->getStoreCategories() as $_category): ?>
    <?php if ($_category->getIsActive()): ?>
        <option value="<?php echo $_category->getId(); ?>"><?php echo $_category->getName(); ?></option>
    <?php endif; ?>
<?php endforeach; ?>
</select>

Note: This is for top level categories only. If you want to get child categories, too, then you can get them with something like:

<?php if ($_category->hasChildren()): ?>
    <?php $category = Mage::getModel('catalog/category')->load($_category->getId()); ?>
        <?php foreach ($category->getChildrenCategories() as $subcategory): ?>
            <?php if ($subcategory->getIsActive()): ?>
                <?php echo $helper->getCategoryUrl($subcategory); ?>
                <?php echo $subcategory->getName(); ?>
                <?php /* etc... */ ?>
            <?php endif; ?>
        <?php endforeach; ?>
<?php endif; ?>

Upvotes: 5

Related Questions