php 如何在 Magento 中获取类别名称?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16955770/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get Category name in Magento?
提问by Sajeev Rajan
I'm new to Magento. I have a 'select-box' that list all the main 'categories-name'. How to get 'Category-name' in Magento?
我是 Magento 的新手。我有一个“选择框”,列出了所有主要的“类别名称”。如何在 Magento 中获得“类别名称”?
回答by Sajeev Rajan
<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>
回答by enenen
Firstly get Catalog->Category helper:
首先获取 Catalog->Category helper:
$helper = Mage::helper('catalog/category');
Location: app/code/core/Mage/Catalog/Helper/Category.php
位置: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; ?>