【问题标题】:Get Subcategory in Magento在 Magento 中获取子类别
【发布时间】:2013-08-25 19:21:40
【问题描述】:

我需要帮助。我使用此代码在 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

我遇到的问题是我希望脚本显示类别最接近产品,但它显示的是根类别(网站的默认类别) 米 谢谢。

【问题讨论】:

    标签: php magento magento-1.7 categories


    【解决方案1】:

    试试这样的:

    <?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;?>
    

    【讨论】:

      【解决方案2】:

      您可以使用array_pop,而不是使用foreach 遍历数组一次。 无论如何,函数 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>
      

      【讨论】:

        猜你喜欢
        • 2013-09-02
        • 1970-01-01
        • 1970-01-01
        • 2011-07-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-03-27
        • 1970-01-01
        相关资源
        最近更新 更多