magento 獲取分類及其子分類 多種情況舉例
阿新 • • 發佈:2019-02-03
1. 獲取指定分類id 下的子分類
// 例如獲取 分類id為 13 的子分類資訊
<?php $root = Mage::getModel('catalog/category')->load(13); $subCat = explode(',',$root->getChildren()); $collection = $root ->getCollection() ->addAttributeToSelect("*") ->addFieldToFilter("entity_id", array("in", $subCat) ); foreach($collection as $catname){ echo $catname->getName(); echo '<br>'; echo $catname->getUrl(); } ?> echo '<br>'; //echo $catname->getProductCount(); //獲取目錄下的產品數量 //echo $catname->getChildrenCount(); //獲取目錄下子目錄數量
2. 顯示所有分類和子分類
<?php $_helper = Mage::helper('catalog/category') ?> <?php $_categories = $_helper->getStoreCategories() ?> <?php if (count($_categories) > 0): ?> <ul> <?php foreach($_categories as $_category): ?> <li> <a href="<?php echo $_helper->getCategoryUrl($_category) ?>"> <?php echo $_category->getName() ?> </a> <?php $_category = Mage::getModel('catalog/category')->load($_category->getId()) ?> <?php $_subcategories = $_category->getChildrenCategories() ?> <?php if (count($_subcategories) > 0): ?> <ul> <?php foreach($_subcategories as $_subcategory): ?> <li> <a href="<?php echo $_helper->getCategoryUrl($_subcategory) ?>"> <?php echo $_subcategory->getName() ?> </a> </li> <?php endforeach; ?> </ul> <?php endif; ?> </li> <?php endforeach; ?> </ul> <?php endif; ?>
3.獲取所有的一級分類資訊
<?php $_helper = Mage::helper('catalog/category') ?> <?php $_categories = $_helper->getStoreCategories() ?> <?php if (count($_categories) > 0): ?> <ul> <?php foreach($_categories as $_category): ?> <li> <a href="<?php echo $_helper->getCategoryUrl($_category) ?>"> <?php echo $_category->getName() ?> </a> </li> <?php endforeach; ?> </ul> <?php endif; ?>
4.獲取所有的一級分類和當前分類的子分類資訊
<?php $_helper = Mage::helper('catalog/category') ?>
<?php $_categories = $_helper->getStoreCategories() ?>
<?php $currentCategory = Mage::registry('current_category') ?>
<?php if (count($_categories) > 0): ?>
<ul>
<?php foreach($_categories as $_category): ?>
<li>
<a href="<?php echo $_helper->getCategoryUrl($_category) ?>">
<?php echo $_category->getName() ?>
</a>
<?php if ($currentCategory && $currentCategory->getId() == $_category->getId()): ?>
<?php $_category = Mage::getModel('catalog/category')->load($_category->getId()) ?>
<?php $_subcategories = $_category->getChildrenCategories() ?>
<?php if (count($_subcategories) > 0): ?>
<ul>
<?php foreach($_subcategories as $_subcategory): ?>
<li>
<a href="<?php echo $_helper->getCategoryUrl($_subcategory) ?>">
<?php echo $_subcategory->getName() ?>
</a>
</li>
<?php endforeach; ?>
</ul>
<?php endif; ?>
<?php endif; ?>
</li>
<?php endforeach; ?>
</ul>
<?php endif; ?>
<< --- 程式碼整理自網路蒐集總結 --->>