我一直在获取产品集合中的产品网址。我有这段代码来获取设置特色产品的产品集合。

 $_productCollection = Mage::getModel('catalog/product')
                  ->setStoreId(Mage::app()->getStore()->getId())
                  ->getCollection();

 $_productCollection->addAttributeToFilter('feat_enabled', 1);
 $_productCollection->setVisibility(array(2,3,4));
 $_productCollection->addUrlRewrite();
 $_productCollection->groupByAttribute('entity_id');
 $_productCollection->load();

foreach($_productCollection as $_product){
       $_product->load($_product->getId());
   if($_product->getIsSalable()){
          $_name = ltrim(rtrim($_product->getName()));
          $_url =  $_product->getProductUrl();
       }
}

我在这里做错了什么,如果在每个循环中都回显 $_url,则缺少返回的 url。它没有类别名称和子类别名称。正确的网址应该是:



但目前它只返回
  index.php/itemname.html

它返回除 url 之外的更正数据。如果我将项目分配给一个类别和子类别,我会在管理员中仔细检查,我确认我分配了它。
Upon further research, I have found the code below that is very close to what i need.
$_categories = $_product->getCategoryIds();
$_category = Mage::getModel('catalog/category')->load($_categories[0]);
$_url = Mage::getUrl($_category->getUrlPath()).basename($_product->getProductUrl());

问题就在这里,$_url 的值变成了这样



子类别名称中包含 .html。我的 url 中不需要 .html,因此单击时该项目将被重定向到正确的页面。

有什么想法可以解决这个问题吗?

最佳答案

问题在于产品可以出现在多个类别中。

因此,在某种程度上,无论您采用哪种方法,您都必须在某处涉及一个类别。

因此,最简洁的方法是使用 addurlRewrite 方法并传递类别 ID。 Magento 将检查与类别 id 和产品 id 匹配的重写 - 如果找到重写,您将在 getProductUr l 调用中获得您正在寻找的漂亮网址。例如,使用类别 ID 10:

$collection = Mage::getResourceModel('catalog/product_collection')
                ->addUrlRewrite(10);

如果您知道每个产品只会出现在一个类别中,那么您可以通过使用以下内容获取第一个类别 ID 来使其更加灵活:

因此,使用此方法的完整示例是:
$categoryId = array_shift($_product->getCategoryIds());
$collection = Mage::getResourceModel('catalog/product_collection')
                ->addUrlRewrite($categoryId);

关于Magento getProductUrl() 没有返回正确的 url,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/10997108/

10-12 16:44
查看更多