2013-08-25 57 views
1

我需要帮助。我用这个代码来获得在产品信息上几页在Magento的类别链接:在Magento中获取子类别

<?php $categories = $_product->getCategoryIds(); ?> 
<span>In </span> 
<?php $i=1; foreach($categories as $k => $_category_id): ?> 
<?php if($i>1) {break;} ?> 
<?php $_category = Mage::getModel('catalog/category')->load($_category_id) ?> 
       <a class="in-category" href="<?php echo $_category->getUrl() ?>"><?php echo $_category->getName() ?></a> 
<?php $i++; endforeach; ?> 

你可以在这里看到:我有http://192.241.178.130/new_arrivals

问题是,我希望脚本显示类别离产品最近但它代替显示根类别(网站的默认类别) M 谢谢。

<?php 
$categoryIds = $_product->getCategoryIds(); 
$categories = Mage::getModel('catalog/category') 
    ->addAttributeToSelect('url_key')//add url key to select 
    ->addAttributeToSelect('name')//add name to select 
    ->getCollection() //get categories as collection 
    ->addAttributeToFilter('entity_id', $categoryIds)//filter only by selected ids 
    ->addAttributeToFilter('is_active', 1)//get only active categories 
    ->addAttributeToFilter('level', array('gte'=>2))//ignore root category and 'root of roots' 
    ->setOrder('level', 'desc');//sort by level descending 
$mainCategory = $categories->getFirstItem();//get only the category lowest in the tree 
if ($mainCategory->getId()) : ?> 
    <a class="in-category" href="<?php echo $mainCategory->getUrl() ?>"><?php echo $mainCategory->getName() ?></a> 
<?php endif;?> 

回答

4

尝试这样的事情。 无论如何,函数getCategoryIds()将返回产品所有类别的数组。这也包括父类别,并且按照逻辑顺序。具有最低ID的类别将首先显示。

也许这样的事情会为你工作:

<?php $_category_id = array_pop($_product->getCategoryIds()); ?> 
<span>In </span> 
<?php $_category = Mage::getModel('catalog/category')->load($_category_id) ?> 
<a class="in-category" href="<?php echo $_category->getUrl() ?>"> 
    <?php echo $_category->getName() ?> 
</a> 
0

使用foreach通过你可以使用array_pop数组走一个时间,而不是: