How do display products by category id in template page(.phtml page) in magento?

帅比萌擦擦* 提交于 2020-01-03 03:36:27

问题


i am new to magento. i used below code in allproduct.phtml file for get all category id's.

function get_categories(){

$category = Mage::getModel('catalog/category'); 
$tree = $category->getTreeModel(); 
$tree->load();
$ids = $tree->getCollection()->getAllIds(); 
$arr = array();
if ($ids){ 
foreach ($ids as $id){ 
$cat = Mage::getModel('catalog/category'); 
$cat->load($id);
$arr[$id] = $cat->getName();
} 
}

return $arr;

}

now i got category Id'd like below in one array,

Array
(
    [Root Catalog] => 1
    [Default Category] => 2
    [Multivitamins] => 3
    [Vitamins and Minerals] => 4
    [Joints and Arthritis] => 5
    [EFA's] => 6
    [Diet and Digestion] => 7
    [Mood, Mind and Specialty] => 8
    [cardiostrong™] => 9
    [Teas and Juices] => 10
    [Additional] => 11
)

Now i need to display all the products seperated by the above category id's.

How can i do this?.


回答1:


You can obtain the products in a category by calling $category->getProductCollection().

Sample:



$categories = Mage::getModel('catalog/category')->getCollection()->addAttributeToSelect('name');

foreach ($categories as $category) { $products = $category->getProductCollection()->addAttributeToSelect('name'); echo sprintf("< h1>%d. %s", $category->getId(), $category->getName()); foreach ($products as $product) { echo sprintf("%d. %s< br />", $product->getId(), $product->getName()); } }

edit: I made the html tags wrong on purpose, to prevent them from being parsed.



来源:https://stackoverflow.com/questions/10801391/how-do-display-products-by-category-id-in-template-page-phtml-page-in-magento

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!