How do display products by category id in template

2019-06-08 11:54发布

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条回答
我只想做你的唯一
2楼-- · 2019-06-08 12:38

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.

查看更多
登录 后发表回答