2013-08-25 60 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數組走一個時間,而不是: