Display Parent Category Products on Subcategory Page in Magento

categorycategory-productscategory-tree

Let's say I have a simple categories tree like this one :

  • Category 1
    • Subcategory 1.1
    • Subcategory 1.2
    • Subcategory 1.675

Some products should be visible for all subcategories, without having to manually select the 675 subcategories. I'd like to only assign these products to Category 1. Then, when I go to Subcategory 1.675 page, I should see products directly assigned to Subcategory 1.675, but also those assigned to Category 1.

How to get this behavior ? A module, or some custom code to change product listing query ?

Best Answer

I think an optimal solution for this would entail that a product collection for a given subcategory includes products belonging to its parent category, if the subcategory is flagged to allow such behavior.

Essentially, it comes down to adding an additional category (parent) filter to the product collection when you're on category 1.675, so that products in both 1 and 1.675 show up on. Here are the steps.

  1. Create a category yes/no attribute. Something like include_parent_products/"Include parent products on display?". Once added, go to the category manage page for 1.675 and flag it yes.
  2. Rewrite Mage_Catalog_Model_Layer::getProductCollection to load a modified collection if setting in step 1 is true.

    $displayParentProducts = $this->getCurrentCategory()->getIncludeParentProducts();
    if ($displayParentProducts) {
        $collection = $this->getCurrentCategory()->getProductCollectionIncludingParents();
    } else {
        $collection = $this->getCurrentCategory()->getProductCollection();
    }
    
  3. Rewrite/Create a new method Mage_Catalog_Model_Category::getProductCollectionIncludingParents.

    public function getProductCollection()
    {
        $parentCategory = ...; // Find parent category
        $collection = Mage::getResourceModel('catalog/product_collection')
            ->setStoreId($this->getStoreId())
            ->addCategoryFilter($this)
            ->addCategoryFilter($parentCategory)
            ;
        return $collection;
    }
    

With the above completed, category 1.675 will now display its products and its parent's as well.

Related Topic