开发者

How do I get product category information using collections in Magento

开发者 https://www.devze.com 2022-12-22 21:49 出处:网络
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. Can anyone suggest how I can do

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. Can anyone suggest how I can do this?

$product = Mage::getModel('catalog/product'); 
$productCollection = $product->getCollection()
->addAttributeToSelect('*');


foreach ( $productCollection as $_product ) {
    echo $_product->getName()开发者_如何学JAVA.'<br/>';        
}


In some instances $_product->getCategory() can return empty and cause an error.

A better solution is to fetch categories by 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

0

精彩评论

暂无评论...
验证码 换一张
取 消