[英]How do I get product category information using collections in Magento
I am trying to output all the products from our Magento shop - the following code works, however I also need to grab the category id & the parent category name too. 我正在尝试从我们的Magento商店输出所有产品 - 以下代码有效,但我也需要获取类别ID和父类别名称。 Can anyone suggest how I can do this? 谁能建议我怎么做?
$product = Mage::getModel('catalog/product');
$productCollection = $product->getCollection()
->addAttributeToSelect('*');
foreach ( $productCollection as $_product ) {
echo $_product->getName().'<br/>';
}
In some instances $_product->getCategory() can return empty and cause an error. 在某些情况下,$ _product-> getCategory()可以返回空并导致错误。
A better solution is to fetch categories by ID: 更好的解决方案是按ID获取类别:
$categoryIds = $_product->getCategoryIds();
foreach($categoryIds as $categoryId) {
$category = Mage::getModel('catalog/category')->load($categoryId);
echo $category->getName();
echo $category->getUrlPath();
}
Since products can be assigned to multiple categories, I think your concept may be a bit off unless you are loading a collection for each category. 由于产品可以分配到多个类别,我认为除非您为每个类别加载集合,否则您的概念可能有点过时。 What do you anticipate seeing if there are multiple categories for a given product? 如果给定产品有多个类别,您预计会看到什么?
Regardless, from within a category page, you can use the following: 无论如何,在类别页面中,您可以使用以下内容:
$currentCat = $_product->getCategory();
To get all categories to which this product belongs: 要获取此产品所属的所有类别:
$categories = $_product->getCategoryCollection();
foreach($categories as $_category) {
// do something
}
Hope that helps. 希望有所帮助。 Thanks, 谢谢,
Joe 乔
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.