My products have an attribute with possible values like "Shampoo", "Masque", etc...

How do i select all sub categories of the current category that contain products of type eg "Shampoo". I want to list categories, not products.

Thank you

  • For what purpose? Are you referring to frontend or backend? – JamesAllwood May 14 '14 at 11:50
  • I am referring to Frontend. For design purposes. I want to create a page to list only (sub)categories (not products) with the option to filter them based on their products. – kbariotis May 14 '14 at 13:31
  • My page is ready. What i need is a way to filter the categories using Magento's ORM. – kbariotis May 14 '14 at 13:32

First get the current category.
Let's say it has the id 4.

$currentCategory = Mage::getModel('catalog/category')->load(4);

Depending on context you might be able to get it like this:

$currentCategory = Mage::registry('current_category');

Now get all the products with the value 'shampoo' for your attribtue.

$collection = Mage::getModel('catalog/product')->getCollection()
    ->addAttributeToFilter('your_attribute_code', 'Shampoo'); 
    //if your attribute is dropdown then replace 'Shampoo' with the id of the option
$collection->addCategoryFilter($currentCategory); //filter products only from the current category if needed

get all children of the current category.

$children = $currentCategory->getChildrenCategories();

add the product count to the children collection


Then you can loop through all the children and see if product_count is bigger than 0.

foreach ($children as $child) {
    if ($child->getProductCount() > 0) {
        //do something with $child.
  • Would you please explain it a little bit? I tried and seemed like $child->getProductCount() always return 0. – kbariotis Jun 27 '14 at 21:08
  • @kostaskostarelo. This is strange. It worked for me. I took the code from the layered navigation. Look how the method Mage_Catalog_Model_Layer_Filter_Category::_getItemsData works. – Marius Jun 27 '14 at 21:16

$childCat = Mage::getModel('catalog/category') ->getCollection()->addAttributeToFiler('parent_id',$current_cat_Id) ->addAttributeFilter('entity_id');

foreach($childCat as $t)

 $collection = Mage::getModel('catalog/product')->getCollection()
        ->addAttributeToFilter('your_attribute_code', 'Shampoo'); 

 $collection->joinField('category_id', 'catalog/category_product', 'category_id', 'product_id = entity_id', null, 'left')
 ->addAttributeToFilter('category_id', array(
     array('finset' => implode( $chhid)),
  • your code doesn't work. :/ – kbariotis Jun 27 '14 at 21:12
  • I just want to add selected category in observer, how can i call selected category? @Amit – zus Aug 2 '19 at 11:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.