Magento display all categories on product view pag

2020-03-31 05:47发布

问题:

Following on from this question: Display ALL categories that a product belongs to in Magento

Is there a way to display the full category path (with links at each stage) rather than only displaying the final category that a product belongs to?

I have this code so far...

<?php
            $currentCatIds = $_product->getCategoryIds();
            $categoryCollection = Mage::getResourceModel('catalog/category_collection')
                 ->addAttributeToSelect('name')
                 ->addAttributeToSelect('url')
                 ->addAttributeToFilter('entity_id', $currentCatIds)
                 ->addIsActiveFilter();
            foreach($categoryCollection as $cat){
            ?>
                <a href="<?php echo $cat->getUrl(); ?>">
                    <?php echo $cat->getName() ?>
                </a>
            <?php } ?>

Which correctly links the category name that is displayed on the page. What I would like is to display the full Cat > Sub Cat > Sub Sub Cat trail, and have each element in that trail correctly linked.

回答1:

How about this:

foreach($categoryCollection as $cat){
    $parents = $cat->getCollection()
        ->addIdFilter($cat->getParentIds())
        ->addAttributeToSelect('name')
        ->addUrlRewriteToResult()
        ->setOrder('level');
    foreach ($parents as $parentCat) {
        // Build your parent links
    }
}

By the way, this kind of code doesn't belong in the template. It should go into a method of the block being rendered (or at least into a helper).