Listing a Category’s Products on Any Magento Page
Sometimes a landing page or custom block needs to show the products from a single category. In Magento 1 that takes a product collection filtered by category, plus two filters for status and visibility.
Loading the products
Swap in your category ID and drop this into a template or block:
<?php
$categoryId = (int category number);
$category = Mage::getModel('catalog/category')->load($categoryId);
$productcollection = Mage::getResourceModel('catalog/product_collection')
->addCategoryFilter($category)
->addAttributeToSelect('*');
/***************************************************
Applying status and visibility filter to the product collection
i.e. only fetching visible and enabled products
****************************************************/
Mage::getSingleton('catalog/product_status')
->addVisibleFilterToCollection($productcollection);
Mage::getSingleton('catalog/product_visibility')
->addVisibleInCatalogFilterToCollection($productcollection);
/**
* Printing category and products name
*/
echo '<h1><strong>'.$category->getName().'</strong></h1>';
foreach ($productcollection as $val) {
echo $val->getName() . '<br />';
}
?>
Why the extra filters matter
Without the next two lines, the collection would include disabled products and items hidden from the catalogue. These filters keep the list limited to products shoppers are allowed to see:
<?php
Mage::getSingleton('catalog/product_status')
->addVisibleFilterToCollection($productcollection);
Mage::getSingleton('catalog/product_visibility')
->addVisibleInCatalogFilterToCollection($productcollection);
?>
From there, loop over the collection and output whatever markup your design needs, such as image, price and add-to-cart button.
Heads up: this guide applies to Magento 1, which stopped receiving official security updates in June 2020. If your store still runs it, plan a move to Magento 2 or Adobe Commerce soon. We can help with the migration.
Want this done for you? Find out more about our Magento development service.