1

I have a Product in my Magento shop. It is in Category C.

My architecure is Category A > Category B > Category C.

With my code below, this displays Category B when on the Product page. How would I adapt the code below to display Category A instead?

if(Mage::registry('current_product')) {

    $_category = Mage::registry('current_category');
    $parentCategoryId = $_category->getParentId();
    $parentCategory = Mage::getModel('catalog/category')->load($parentCategoryId);

    $url = strtolower(str_replace(" ","-",$parentCategory->name));

    echo '<a href="/'.$url.'">'.$parentCategory->name.'</a>';

}

I had thought of maybe using the number of '/' in the URL to change my code.

Many thanks for any pointers with this.

4

1 回答 1

2

类别 C的父类别是类别 B,而不是类别A。要获取给定产品的顶级父类别,您需要爬上类别树:

$category = Mage::registry('current_category');

while ($category->getLevel() != 2) {
    $category = Mage::getModel('catalog/category')->load($category->getParentId());
}

每个类别都有一个级别:级别 1 是目录根,级别 2 是顶级类别,超过级别 2 的任何内容都是子类别。

于 2013-07-24T15:06:34.743 回答