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
精彩评论