Hyvä Theme is Now Open Source: What This Means for Magento Community - Mageplaza
Hyvä is now Open Source and free. Discover what changed, what remains commercial, how it impacts the Magento ecosystem, and how to maximize its full potential.
Vinh Jacker | 03-17-2025
Magento 2 is one of the most popular eCommerce platforms available today, and its ability to handle complex and large-scale product catalogs makes it a favorite among merchants. Understanding how to get product collection in Magento 2 is crucial for developers who want to manipulate product data for various tasks, such as building custom reports, integrating third-party services, or improving website performance.
In this guide, we will explore the step-by-step process of retrieving product collections in Magento 2, including best practices, code snippets, and common issues to avoid.
Learn more: Get product collection by category ID in Magento 2
In Magento 2, a product collection refers to a set of products that can be filtered, sorted, and loaded based on specific criteria. This allows developers to work with groups of products rather than individual items, making it easier to apply changes or retrieve information in bulk.
Product collections are used throughout the Magento system, especially in frontend displays like category pages, search results, and product listing pages. Understanding how to retrieve and manipulate these collections is essential for customizing the eCommerce experience.
Getting a product collection can be necessary for various reasons, including:
By learning how to fetch product collections, developers can unlock new possibilities for customizing Magento 2 stores and improving overall functionality.
Before diving into the code, ensure you have a properly configured Magento 2 development environment. You’ll need access to:
With everything in place, you’ll be ready to start working with product collections.
There are different ways to get product collection in Magento 2. This post will guide you in retrieving a product collection in Magento 2 using various conditions such as loading, filtering, and sorting, which will help you effectively manage and display products within your Magento store.
You will use a block class of the module Mageplaza_HelloWorld, then possibly inject the object of \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory in the constructor of the module’s block class.
app/code/Mageplaza/HelloWorld/Block/HelloWorld.php
<?php
namespace Mageplaza\HelloWorld\Block;
class HelloWorld extends \Magento\Framework\View\Element\Template
{
protected $_productCollectionFactory;
public function __construct(
\Magento\Backend\Block\Template\Context $context,
\Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $productCollectionFactory,
array $data = []
)
{
$this->_productCollectionFactory = $productCollectionFactory;
parent::__construct($context, $data);
}
public function getProductCollection()
{
$collection = $this->_productCollectionFactory->create();
$collection->addAttributeToSelect('*');
$collection->setPageSize(3); // fetching only 3 products
return $collection;
}
}
?>
Note: You can request the number of the product collection, which is a limited or unlimited number. While implementing this function, you will need to extend the code based on the requirement.
Print out the product collection in phtml file with the below code:
$productCollection = $block->getProductCollection();
foreach ($productCollection as $product) {
print_r($product->getData());
echo "<br>";
}
Now, you can get the data of each product in the requested collection.
$collection = $this->productCollectionFactory->create();
$collection->addAttributeToSelect(['name','sku']);
$collection->setPageSize(3);
foreach ($collection as $product) {
print_r($product->getData());
}
$collection = $this->productCollectionFactory->create();
$collection->addAttributeToSelect('*');
$collection->setPageSize(3);
foreach ($collection as $product) {
print_r($product->getData());
}
$categories = [1,2,3]; //category ids array
$collection = $this->productCollectionFactory->create();
$collection->addAttributeToSelect('*');
$collection->addCategoriesFilter(['in' => $categories]);
return $collection;
$categoryId = '1';
$category = $this->categoryFactory->create()->load($categoryId);
$collection = $this->productCollectionFactory->create();
$collection->addAttributeToSelect('*');
$collection->addCategoryFilter($category);
$collection->addAttributeToFilter('visibility', \Magento\Catalog\Model\Product\Visibility::VISIBILITY_BOTH);
$collection->addAttributeToFilter('status',\Magento\Catalog\Model\Product\Attribute\Source\Status::STATUS_ENABLED);
return $collection;
$collection = $this->productCollectionFactory->create();
$collection->addAttributeToSelect('*');
$collection->addAttributeToFilter('type_id', ['eq' => 'simple']);
$collection->getSelect()->order('created_at', \Magento\Framework\DB\Select::SQL_DESC);
$collection->getSelect()->limit(10);
return $collection;
NOTE: You can also use the following values for type_id to apply filters for different product types.
$storeid = 1;
$collection = $this->productCollectionFactory->create();
$collection->addAttributeToSelect('*');
$collection->addStoreFilter($storeid);
return $collection;
$website_ids = [1,2];
$collection = $this->productCollectionFactory->create();
$collection->addAttributeToSelect('*');
$collection->addStoreFilter($storeid);
$collection->addWebsiteFilter($websiteIds);
return $collection;
There are various filters available for product collections. Let’s go through each of them individually below.
$collection = $this->productCollectionFactory->create();
$collection->addAttributeToFilter('status', ['eq' => 1]);
$collection = $this->productCollectionFactory->create();
$collection->addAttributeToFilter('status', ['neq' => 1]);
$collection = $this->productCollectionFactory->create();
$collection->addAttributeToFilter('price', ['gt' => 100]);
$collection = $this->productCollectionFactory->create();
$collection->addAttributeToFilter('price', ['gteq' => 100]);
$collection = $this->productCollectionFactory->create();
$collection->addAttributeToFilter('price', ['lt' => 100]);
$collection = $this->productCollectionFactory->create();
$collection->addAttributeToFilter('price', ['lteq' => 100]);
$collection = $this->productCollectionFactory->create();
$collection->addAttributeToFilter('sku', ['like' => '%Bag%']);
$collection = $this->productCollectionFactory->create();
$collection->addAttributeToFilter('sku', ['nlike' => '%Bag%']);
$collection = $this->productCollectionFactory->create();
$collection->addAttributeToFilter('entity_id', ['in' => [1,2]]);
$collection = $this->productCollectionFactory->create();
$collection->addAttributeToFilter('entity_id', ['nin' => [1,2]]);
$collection = $this->productCollectionFactory->create();
$collection->addAttributeToFilter('description', ['null' => true]);
$collection = $this->productCollectionFactory->create();
$collection->addAttributeToFilter('description', ['notnull' => true]);
Similar to filters, there are various ways to sort your product collection. Let’s explore them below.
$collection = $this->productCollectionFactory->create();
$collection->getSelect->order('sku', 'ASC');
Or
$collection = $this->productCollectionFactory->create();
$collection->setOrder('sku', 'ASC');
$collection = $this->productCollectionFactory->create();
$collection->getSelect->order('sku', 'DESC');
Or
$collection = $this->productCollectionFactory->create();
$collection->setOrder('sku', 'DESC');
$collection = $this->productCollectionFactory->create();
$collection->setPageSize(50)->load();
$collection = $this->productCollectionFactory->create();
$collection->setPageSize(50)->setCurPage(2)->load();
$collection = $this->productCollectionFactory->create();
echo $collection->count();
$collection = $this->productCollectionFactory->create();
$collection->getSelect()->group('entity_id');
$collection = $this->productCollectionFactory->create();
echo $collection->getSelect()->__toString();
While retrieving product collections in Magento 2 is straightforward, there are some common pitfalls to watch out for:
php bin/magento indexer:reindex to update the indexes.Avoiding these common mistakes will ensure that your product collections perform optimally.
To summarize, here are some best practices to follow when retrieving product collections in Magento 2:
Following these best practices will help you write clean, efficient code that performs well.
Understanding how to get product collection in Magento 2 is an essential skill for developers working with the platform. By mastering product collections, you can manipulate product data effectively, improve site performance, and provide custom functionality to meet specific business needs. Whether you’re creating custom product filters, integrating with third-party systems, or building tailored frontend experiences, product collections are a versatile and powerful tool in Magento 2 development.
By following the steps outlined in this guide and adhering to best practices, you’ll be able to get and manipulate product collections with ease. Happy coding!