1

Trying to get the product count of a category which also counts the products in its children. Currently, I have:

$categories = Mage::getModel('catalog/category')->getCollection()
        ->addAttributeToSelect('*')
        ->addAttributeToFilter('level', 2)
        ->addAttributeToSelect('is_active', 1);

 foreach ($categories as $cat) {
      echo count($cat->getProductCollection());
 }

however this returns the product count of the parent category without counting its child category products. How do I include the child categories in the parent count?

123TFO
  • 109
  • 3
  • 12

3 Answers3

1

I figured it out - here's my code for anyone who has the same issue:

public function countProductsInCategory() {
       $parentCategories = $this->getParentCategories();

       //sets up the arrays
       $parentArray      = array();//parent categories
       $valueArray       = array();//the count of the child category products
       $tmp              = array();//merging of the two

       foreach ($parentCategories as $_parent) {
           $parentCat   = Mage::getModel('catalog/category')->load($_parent->getId());
           $parentCount = $parentCat->getProductCount();
           $children    = $_parent->getChildrenCategories();
           $i           = $parentCount;

           $parentArray[$_parent->getName()][] = $i;

           foreach ($children as $_child) {
                $childCat   = Mage::getModel('catalog/category')->load($_child->getId());
                $childCount = $childCat->getProductCount();

                $parentArray[$_parent->getName()][] = $childCount;
            }
        }

        foreach ($parentArray as $val) {
            $valueArray[] = array_sum($val);
        }

        $i = 0;//start i as 0

        foreach ($parentCategories as $name) {
            $tmp[$i] = array('name' => $name->getName(), 'url' => $name->getUrl());
            $i++;
        }

        $i = 0;//reset $i to 0 to match indexes

        foreach ($valueArray as $val) {
            $tmp[$i]['value'] = $val;
            $i++;
        }

        return $tmp;
    }
123TFO
  • 109
  • 3
  • 12
0

You can use for get product count of a specific category.

$productsCount = Mage::getModel('catalog/category')->load($category->getId())
 ->getProductCount();

echo($productsCount);

You can use here $category->getId() replace category ID as static. Here you replace category ID which you want get product count.

  • Hi this only gets the product count of that category - it doesn't include the children categories or its products to the parent :( – 123TFO Jun 28 '16 at 08:09
0

Try this:

$categories = Mage::getModel('catalog/category')->getCollection()
    ->addAttributeToSelect('*')
    ->addAttributeToFilter('level', 2)
    ->addAttributeToSelect('is_active', 1)
    ->setLoadProductCount(true);

foreach ($categories as $category) {
    echo $category->getProductCount();
} 
Marius
  • 197,939
  • 53
  • 422
  • 830