dongwo5940 2013-08-25 19:21
浏览 58
已采纳

获取Magento的子类别

I need help. I use this code to get the category link under products info on a few pages in 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; ?>

You can see it here: http://192.241.178.130/new_arrivals

Problem I'm having is that I want the script to display the category closest to the product but it's instead displaying the root category (Default category of the site) M Thanks.

  • 写回答

2条回答 默认 最新

  • ds19891231 2013-08-25 20:31
    关注

    Try something like this:

    <?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;?>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥30 自适应 LMS 算法实现 FIR 最佳维纳滤波器matlab方案
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来
  • ¥15 求帮我调试一下freefem代码
  • ¥15 matlab代码解决,怎么运行
  • ¥15 R语言Rstudio突然无法启动