How to Get Product Collection in Magento?

Magento Get Product Collection: There are sometimes requirements to find product collection in Magento as per its code structure and with this blog we are going to share the syntax that you can use to get the desired effect.


Magento Get All product Collection Syntax

$Collection = Mage::getModel('catalog/product')
                        ->getCollection()
                        ->addAttributeToSort('created_at', 'DESC')
                        ->addAttributeToSelect('*')
                        ->load();
foreach ($Collection as $_product){
   echo $_product->getId().'</br>';
   echo $_product->getName().'</br>';
   echo $_product->getPrice().'</br>';
}

Magento product collection order can be set by ascending or descending as per the requirements of the layout respectively. Here are the codes for the following.

Magento get product collection order by Descending

ORDER BY Attribute Descending:-

$Collection ->addAttributeToSort('created_at', 'DESC')

Magento get product collection order by Ascending

ORDER BY Attribute Ascending:-

$Collection ->addAttributeToSort('created_at', 'ASC')

Magento Get Product Collection Set Limit

If  you want your product collection but you want to limit the number of results to a certain product you can use the ‘setPageSize()’ method and simply pass in your limit.

$collection = Mage::getModel('catalog/product')
                        ->getCollection()
                        ->addAttributeToSort('created_at', 'DESC')
                         ->setPageSize(5);
                        ->load();
foreach ($Collection as $_product){ 
echo $_product->getId().'</br>'; 
echo $_product->getName().'</br>'; 
echo $_product->getPrice().'</br>';
}

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *