2
votes

When someone clicks on a parent category page I want all the products listed there to be divided by their child categories, such as the following:

(clicking on parent category 'apparel')

Shirts: [shirt #1] [shirt #2] [ shirt #3]

Pants: [pants #1] [pants #2] [pants #3]

Socks: [socks #1] [socks #2] [socks #3]

The setup I have is the parent category 'apparel' has three children 'shirts', 'pants', and 'socks'. When the 'apparel' category page is shown it just lists all products without grouping them under their respective subcategories.

I am using Magento Community 1.7.0.2

1

1 Answers

0
votes

One way to do it:

Get all child categories

$category_model = Mage::getModel('catalog/category')->load($currentCategoryId); 
$all_child_categories = $category_model->getResource()->getAllChildren($_category);

Get all the category's products

$productCollection = Mage::getResourceModel('catalog/product_collection')
                       ->addCategoryFilter($category);

Edit:

In order to get subcategory products follow these steps:

Go to this template file (here is where you can put all the code listed below):

catalog/product/list.phtml

Get the current category ID:

$currentCategory = Mage::registry('current_category');
$currentCategoryID = $currentCategory->getEntityId();

Load the current category model to get the category children:

$category_model = Mage::getModel('catalog/category')->load($currentCategoryID);

Get all the child category id's:

$all_child_categories = $category_model->getResource()->getAllChildren($category_model );

Loop through each child id and load the category and it's children:

foreach ($all_child_categories as $child_id):
    $child_cat = Mage::getModel('catalog/category')->load($child_id);
    $products =  Mage::getResourceModel('catalog/product_collection')
                   ->addCategoryFilter($child_cat);
endforeach;

Let us know if yo need further assistance