如何获取当前类别的根父类别及其所有子类别

时间:2015-12-21 11:24:52

标签: magento parent categories

我需要逻辑来显示类别树,如下所示:

Cat1 -> cat11 -> cat111   
Cat2 -> cat21 -> cat211  
Cat3 -> cat31 -> cat311

因此,如果我在cat211中,则在左栏中应显示其根父类别(Cat2)的所有类别。例如。在magento

Cat2 - > Cat21 - > Cat211

2 个答案:

答案 0 :(得分:0)

我猜你的意思是类别树,这应该给你类别树。您可以看到正在应用的各种过滤器。 (你可以随时根据自己的需要做。)

<?php
$rootCatId = Mage::app()->getStore()->getRootCategoryId();
$catlistHtml = getTreeCategories($rootCatId, false);
echo $catlistHtml;

function getTreeCategories($parentId, $isChild){
$allCats = Mage::getModel('catalog/category')->getCollection()
            ->addAttributeToSelect('*')
            ->addAttributeToFilter('is_active','1')
            ->addAttributeToFilter('include_in_menu','1')
            ->addAttributeToFilter('parent_id',array('eq' => $parentId))
            ->addAttributeToSort('position', 'asc');

$class = ($isChild) ? "sub-cat-list" : "cat-list";
$html .= '<ul class="'.$class.'">';
foreach($allCats as $category)
{
    $html .= '<li><span>'.$category->getName()."</span>";
    $subcats = $category->getChildren();
    if($subcats != ''){
        $html .= getTreeCategories($category->getId(), true);
    }
    $html .= '</li>';
}
$html .= '</ul>';
return $html;
}

?>
  

编辑:使用ID /当前类别ID获取所有父类别。

$id = Mage::registry('current_category'); //or if you are retrieving other way around
$category = Mage::getModel('catalog/category')->load($id);

$categorynames = array();
foreach ($category->getParentCategories() as $parent) {
    $categorynames[] = $parent->getName();
}
print_r($categorynames); //dumping category names for eg.

答案 1 :(得分:0)

属性path包含1/root_id/parent_id/.../category_id形式的所有父ID。您可以使用$category->getPathIds()将其作为数组进行检索(如果要排除类别本身的ID,则可以$category->getParentIds())。因为路径中的第一个ID始终是&#34; 1&#34;,所以您应该删除第一个数组项以从商店根类别开始:

$categoryIds = $category->getPathIds();
array_shift($categoryIds);

然后您可以使用集合一次加载这些:

$categoryCollection = $category->getCollection()->addIdFilter($categoryIds);
foreach ($categoryCollection as $categoryInPath) {

    // do what you want with $categoryInPath

}
相关问题