Charlie Harvey

Magento tip: Number of products in category, subcategories of a store

I had need today of counting the total number of products in a category and all its subcategories in one of the magento stores that New Internationalist runs. It took a little while to write the code so I am putting it out there in case anyone else has the same problem. Most probably my future self.

require_once '/var/www/live.magento/app/Mage.php'; $category_id = 4321; $store_id = 6; Mage::init(); $_category = Mage::getModel('catalog/category')->load($category_id); $_total = products_in_category($_category); echo "TOTAL products in category and subcategories: $_total\n"; # Takes a category, returns total number of products in the category, plus # any subcategories. function products_in_category($category) { global $store_id; $_subcategories = Mage::getModel('catalog/category')->getCategories($category->getEntityId()); foreach($_subcategories as $cat) { if($cat->getIsActive()) { $_category = Mage::getModel('catalog/category')->load($cat->getEntityId()); $total += products_in_category($_category); } } $_products = Mage::getResourceModel('catalog/product_collection') ->addCategoryFilter($category) ->setStoreId($store_id) ->addStoreFilter($store_id); Mage::getSingleton('catalog/product_status')->addVisibleFilterToCollection($_products); Mage::getSingleton('catalog/product_visibility')->addVisibleInCatalogFilterToCollection($_products); echo "Category " . $category->getName(). ": " . $_products->count() . " live, visible products.\n"; return $total + $_products->count(); }

You set the category and store_id you are interested in near the top, then the script crawls through your categories recursively echoing the number of products in each category and eventually returning the total which is also echoed. Only products that are enabed and with visibility catalog and store will be shown.

Image from wikipedia, used under Creative Commons Attribution-Share Alike 2.0 Generic license


Comments

  • Be respectful. You may want to read the comment guidelines before posting.
  • You can use Markdown syntax to format your comments. You can only use level 5 and 6 headings.
  • You can add class="your language" to code blocks to help highlight.js highlight them correctly.

Privacy note: This form will forward your IP address, user agent and referrer to the Akismet, StopForumSpam and Botscout spam filtering services. I don’t log these details. Those services will. I do log everything you type into the form. Full privacy statement.