Magento Product Collections: Steps to Get Product Collection in Magento 2

Magento Product Collections: Steps to Get Product Collection in Magento 2

Want to enhance your Magento product collections? Magento lets you organize products with powerful filters and sorting tools. It helps customers find what they need faster, creating a better shopping experience.

This tutorial covers steps to configure, filter, and arrange Magento product collections.

Best Magento Hosting now

Key Takeaways

  • Overview of Magento Product Collections

  • Configuration of Product Collections in Magento 2

  • Different Filters in Magento Product Collections

  • Steps to Sort Magento Product Collections

  • Benefits of Using Magento Product Collections

What is Magento Product Collection?

What is Magento Product Collection

A Magento Product Collection shows products in your Magento 2 store. You can organize it with filters and sorting options.

Collections help you display products based on customer needs. This setup improves the shopping experience. It’s more than listing items; it’s about showing products that fit your store’s goals.

Magento 2 offers many ways to use collections. You can load all products or apply filters for specific items. Sorting lets you arrange by price, popularity, or category. Loading gives a broad selection. Filtering narrows options. Sorting speeds up product discovery, boosting satisfaction. These features enhance store performance and make shopping easier.

How to Configure Magento Product Collections?

1. Load Product Collection in Magento 2

To load a product collection, initialize it with a specified page size. It will control the number of items displayed.

<?php

namespace MD\HelloWorld\Block;

class HelloWorld extends \Magento\Framework\View\Element\Template

{

`protected $productCollectionFactory;`

`protected $categoryFactory;`

`public function __construct(`

   `\Magento\Framework\View\Element\Template\Context $context,`

   `\Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $productCollectionFactory,`

   `\Magento\Catalog\Model\CategoryFactory $categoryFactory,`

   `array $data = []`

`){`

   `$this->productCollectionFactory = $productCollectionFactory;`

   `$this->categoryFactory = $categoryFactory;`

   `parent::__construct($context, $data);`

`}`  

`public function getProductCollection()`

`{`

    `$collection = $this->productCollectionFactory->create();`

   `$collection->setPageSize(3);`      

   `foreach ($collection as $product) {`

       `print_r($product->getData());`

   `}`

    `return $collection;`

`}`

}

1.1 Load Product Collection with Specific Attributes

Select only specific attributes like 'name' and 'sku' to streamline the collection data.

$collection = $this->productCollectionFactory->create();

$collection->addAttributeToSelect(['name','sku']);

$collection->setPageSize(3);

foreach ($collection as $product) {

`print_r($product->getData());`

}

1.2 Load Product Collection with All Attributes

Load the complete set of attributes for each product in the collection.

$collection = $this->productCollectionFactory->create();

$collection->addAttributeToSelect('*');

$collection->setPageSize(3);

foreach ($collection as $product) {

`print_r($product->getData());`

}

2. Get Product Collection by Multiple Categories in Magento 2

Filter products by multiple category IDs to display items that fall under specified categories.

$categories = [1,2,3];

$collection = $this->productCollectionFactory->create();

$collection->addCategoriesFilter(['in' => $categories]);

return $collection;

3. Steps to Get Product Collection in Magento by Specific Category

Filter by a single category and display only products that are visible and enabled.

$categoryId = '1';

$category = $this->categoryFactory->create()->load($categoryId);

$collection = $this->productCollectionFactory->create();

$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;

4. Get Product Collection by Product Type

Filter products by a specific product type, such as ‘simple’. Sort results by creation date in descending order.

$collection = $this->productCollectionFactory->create();

$collection->addAttributeToFilter('type_id', ['eq' => 'simple']);

$collection->getSelect()->order('created_at', \Magento\Framework\DB\Select::SQL_DESC);

$collection->getSelect()->limit(10);

return $collection;

5. Get Product Collection by Store ID in Magento 2

Filter collections by store ID to tailor products shown based on the selected store.

$storeid = 1;

$collection = $this->productCollectionFactory->create();

$collection->addStoreFilter($storeid);

return $collection;

6. Get Product Collection by Website IDs

Filter products by website IDs to target items linked to specific Magento websites.

$website_ids = [1,2];

$collection = $this->productCollectionFactory->create();

$collection->addWebsiteFilter($website_ids);

return $collection;

Different Filters You Can Use for Magento Product Collections

Filter Type Description Code Example
Is Equal to Filters products with an attribute equal to a value. $collection = $this->productCollectionFactory->create(); $collection->addAttributeToFilter('status', ['eq' => 1]);
Is Not Equal to Filters are products with an attribute that is not equal to a value. $collection = $this->productCollectionFactory->create(); $collection->addAttributeToFilter('status', ['neq' => 1]);
Greater than Filters products with an attribute greater than a value. $collection = $this->productCollectionFactory->create(); $collection->addAttributeToFilter('price', ['gt' => 100]);
Greater than or Equal to Filters products with an attribute greater than or equal to a value. $collection = $this->productCollectionFactory->create(); $collection->addAttributeToFilter('price', ['gteq' => 100]);
Less than Filters products with an attribute less than a value. $collection = $this->productCollectionFactory->create(); $collection->addAttributeToFilter('price', ['lt' => 100]);
Less than or Equal to Filters products with an attribute less than or equal to a value. $collection = $this->productCollectionFactory->create(); $collection->addAttributeToFilter('price', ['lteq' => 100]);
Like Filters products where an attribute contains a specific substring. $collection = $this->productCollectionFactory->create(); $collection->addAttributeToFilter('sku', ['like' => '%Bag%']);
Not Like Filters products where an attribute does not contain a specific substring. $collection = $this->productCollectionFactory->create(); $collection->addAttributeToFilter('sku', ['nlike' => '%Bag%']);
In Array Filters products with an attribute in an array of values. $collection = $this->productCollectionFactory->create(); $collection->addAttributeToFilter('entity_id', ['in' => [1,2]]);
Not in Array Filters products with an attribute not in an array of values. $collection = $this->productCollectionFactory->create(); $collection->addAttributeToFilter('entity_id', ['nin' => [1,2]]);
NULL Filters products where an attribute is NULL. $collection = $this->productCollectionFactory->create(); $collection->addAttributeToFilter('description', ['null' => true]);
Not NULL Filters products where an attribute is not NULL. $collection = $this->productCollectionFactory->create(); $collection->addAttributeToFilter('description', ['notnull' => true]);

How to Sort Product Collection in Magento 2 Online Stores?

Sorting your product collection helps display items in a specific order and limit results. Here are the steps to sort collections effectively in Magento 2.

1. Order by ASC

To sort products in ascending order, use the sku attribute or any other attribute.

$collection = $this->productCollectionFactory->create();

$collection->setOrder('sku', 'ASC');

2. Order by DESC

To sort products in descending order, use the sku attribute or any other attribute.

$collection = $this->productCollectionFactory->create();

$collection->setOrder('sku', 'DESC');

3. Set Limit for Product Collection

Limit the number of products displayed by setting a specific page size.

$collection = $this->productCollectionFactory->create();

$collection->setPageSize(50)->load();

4. Set Limit with Current Page

Set a page limit and specify the current page to load a subset of products.

$collection = $this->productCollectionFactory->create();

$collection->setPageSize(50)->setCurPage(2)->load();

5. Count Product Collection

To get the total number of products in the collection, use the count() method.

$collection = $this->productCollectionFactory->create();

echo $collection->count();

6. Group by Product Collection

Group the collection by product ID or any other attribute.

$collection = $this->productCollectionFactory->create();

$collection->getSelect()->group('entity_id');

7. Print Collection Query

To view the SQL query for your collection, print the query string.

$collection = $this->productCollectionFactory->create();

echo $collection->getSelect()->__toString();

Benefits of Using Magento Product Collections

Benefits of Magento Product Collections

Benefit Explanation
Efficient Product Organization Magento product collections help you organize items by attributes. This setup lets you categorize products effectively. Customers find items faster, enhancing the shopping experience. Organized collections reduce search time.
Improved Customer Experience Collections let you tailor displays to customer needs, like sales or new arrivals. This setup makes navigation simpler and more enjoyable. Customers engage more and convert faster. Easy-to-find products boost satisfaction and loyalty.
Enhanced Searchability Collections improve search by grouping similar products together. Customers find what they need easily. You can filter collections by specific criteria, making searches accurate. Better searchability drives sales and retention.
Increased Conversion Rates Targeted collections help customers quickly find relevant items. Displaying preferred products boosts purchases. Collections make it easy to promote bestsellers or seasonal items, increasing conversions. Structured stores lead to more sales.
Streamlined Management Managing inventory becomes easier with collections. Update or filter products in bulk. This feature saves time, especially for large catalogs. Adjust collections to match business goals or promotions. It simplifies product management.

FAQs

1. How do I get a product collection by category ID in Magento 2?

To get product collection by category ID in Magento 2, use the addCategoryFilter function. Load the specific category first, then apply it to the collection. It displays only products within that category. This method is efficient for targeted displays.

2. Why use Magento 2 product collections?

Magento 2 product collections organize products by attributes like category and price. This structure improves searchability and the shopping experience. Customers find items faster, boosting satisfaction. Well-managed collections drive conversions and sales.

3. How can I filter Magento 2 product collections by multiple categories?

You can get product collection by category ID for multiple categories. You need to use addCategoriesFilter. This filter accepts an array of category IDs. It allows you to display products from several categories at once. This approach tailors the display to customer needs.

4. How do I sort a Magento 2 product collection?

In Magento 2, use setOrder to sort collections by attributes like price or SKU. Ascending or descending order options are available. Sorting helps you highlight items based on customer interest. It, with dedicated Magento hosting, improves the browsing experience and product visibility.

5. What attributes can be filtered in a Magento 2 product collection?

You can filter Magento 2 product collections by many attributes, including name, price, and SKU. Other options include status, visibility, and product type. These filters refine search results and match products to customer preferences.

CTA

Summary

Magento product collections make product discovery easier and boost overall engagement. Key benefits are:

  • Efficient Organization: Organize items by category or attribute.

  • Enhanced Experience: Help customers find products quickly.

  • Improved Searchability: Use filters and sorting to increase visibility.

  • Higher Conversions: Showcase products customers want to buy.

  • Streamlined Management: Easily update collections to match goals.

Consider managed Magento hosting to configure and organize product collections in Magento accurately.

Shivendra Tiwari
Shivendra Tiwari
Technical Writer

Shivendra has over ten years of experience creating compelling content on Magento-related topics. With a focus on the Magento community, he shares valuable tips and up-to-date trends that provide actionable insights.


Get the fastest Magento Hosting! Get Started