7
votes

How can I get a specific category level from Magento, my category setup looks like this now.

root_catalog
    |-Shop
        |-Shoes
        |-T-shirts
    |-Brands
        |-Nike
           |-Womens
           |-Mens
        |-Adidas
        |-Asics

<?php if( $category = Mage::getModel('catalog/category')->load( $categories[1]) ): ?>
    <?php echo $category->getName(); ?>
<?php endif ?>

When calling $category->getName(); I would like to only display the Brand Name, is that possible?

3

3 Answers

9
votes

You can get category level from $category = Mage::getModel('catalog/category')->load( $categories[1]) )->getLevel() and then check with your brand name category level, if match then display name.

e.g. suppose brand category level is 3

<?php if( $category = Mage::getModel('catalog/category')->load( $categories[1]) ): ?>
    <?php if($category->getLevel() == 3)
        echo $category->getName(); ?>
    <?php endif ?>
<?php endif ?>
5
votes

ANKIT's answer is good, but it could be improved by actually query-ing the specific levels instead of loading the whole collection and doing a conditional. Take for example if you want to get all categories in a specific level:

<ul>
<?php $categories = Mage::getModel('catalog/category')
                         ->getCollection()
                         // magic is prepared here..
                         ->addAttributeToSelect('*')
                         // then the magic happens here:
                         ->addAttributeToFilter('level', array('eq'=>2))
                         ->load();

      foreach($categories as $category):
?>
<li>$category->getName()</li>
<?php endforeach; ?>
</ul>
0
votes
<?php 

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$product = $objectManager->get('Magento\Framework\Registry')->registry('current_product');
$categories = $product->getCategoryIds(); /*will return category ids array*/

foreach($categories as $category){

    $cat = $objectManager->create('Magento\Catalog\Model\Category')->load($category);
    if ($cat->getLevel() == 2) {
        $catName = $cat->getName().","; ?>
        <div class="brand_bg">
            <label><?php /* @escapeNotVerified */ echo __('Category :') ?></label>

            <?php echo $catName; ?>
        </div>
    <?php } ?>
<?php } ?>

?>