Magento为什么目录模型在一个循环中为几个不同的类别返回相同的url


Magento why Catalog Model returns same url for several different categories on a loop?

我想在产品页面上显示类别链接。

所以我这样做:

<?php
$_product = $this->getProduct();
$category_model = Mage::getModel('catalog/category');
$category_helper = Mage::helper('catalog/category');
$categories_ids = $_product->getCategoryIds();
?>
<?php if (count($categories_ids > 0)): ?>
  <ul class="categorias-principais">
    <?php foreach ($categories_ids as $cat_id): ?>
      <?php $category = $category_model->load($cat_id) ?>
      <?php if(!$category->getIsActive()) continue; ?>
      <li>
        <a href="<?php echo $category->getUrl(); ?>">
          <?php echo $category->getName() ?>
        </a>
      </li>
    <?php endforeach ?>
  </ul>
<?php endif ?>

我得到了正确的名称,但url总是等于第一个,对于其他类别,为什么?getName,getUrlPath,都返回正确的值,但不返回getUrl()

我还尝试使用一个助手:

<a href="<?php echo $category_helper->getCategoryUrl($category) ?>">
    <?php echo $category->getName() ?>
</a>

但是问题仍然存在

这是生成的html

<ul class="categorias-principais">
  <li>
    <a href="http://localhost:3000/index.php/maquiagem.html">
      Maquiagem
    </a>
  </li>
  <li>
    <a href="http://localhost:3000/index.php/maquiagem.html">
      Corpo e Banho
    </a>
  </li>
  <li>
    <a href="http://localhost:3000/index.php/maquiagem.html">
      Sub segundo
    </a>
  </li>
  <li>
    <a href="http://localhost:3000/index.php/maquiagem.html">
      Unhas
    </a>
  </li>
</ul>

编辑:

当我使用更改收藏时

$categories = $_product->getCategoryCollection();

我可以成功地使用getUrl(),而不是获取类别ID并用模型加载类别,但随后getName()和getIsActive()将不再工作,所以我混合了这两种实例类型,这非常糟糕,但如果没有人能给我更好的答案,我会把它作为一个发布。

新代码工作:

<?php
$_product = $this->getProduct();
$category_model = Mage::getModel('catalog/category');
$category_helper = Mage::helper('catalog/category');
$categories = $_product->getCategoryCollection();
?>
<?php if (count($categories) > 0): ?>
  <ul class="categorias-principais">
    <?php foreach ($categories as $_category): ?>
      <?php $_category_element = $category_model->load($_category->getId()) ?>
      <?php if(!$_category_element->getIsActive() || $_category->getLevel() != 2) continue; ?>
      <li>
        <a href="<?php echo $_category->getUrl() ?>">
          <?php echo $_category_element->getName() ?>
        </a>
      </li>
    <?php endforeach ?>
  </ul>
<?php endif ?>

使用以下代码,将参数作为类别进行检查,如$_cat->getUrl($_cat);您的第一个代码中没有包含参数。

$product = Mage::getModel('catalog/product')->load($productId);
$cats = $product->getCategoryIds();
foreach ($cats as $category_id) {
$_cat = Mage::getModel('catalog/category')->load($category_id) ;
 echo $_cat->getUrl($_cat);
echo $_cat->getName();
}