How to Get Product Collection by Category ID in Magento 2
Regarding the fast development of Magento, the product collection is becoming increasingly important. This is because in various project, a product collection is usually required in different filters and requirements. Therefore, in today article, I will show you the steps which could help you get product collection by category in Magento 2.
How to get Product Collection by Category ID
Step 1: Create Products.php block
In order to get the product collection by category ID, the first thing you would have to do is creating Products.php
block. Follow this path: Mageplaza/HelloWorld/Block/Products.php
<?php
namespace Mageplaza\HelloWorld\Block;
class Products extends \Magento\Framework\View\Element\Template
{
/**
* @var \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory
*/
protected $_productCollectionFactory;
public function __construct(
\Magento\Backend\Block\Template\Context $context,
\Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $productCollectionFactory
)
{
$this->_productCollectionFactory = $productCollectionFactory;
parent::__construct($context);
}
public function getProductCollectionByCategories($ids)
{
$collection = $this->_productCollectionFactory->create();
$collection->addAttributeToSelect('*');
$collection->addCategoriesFilter(['in' => ids]);
return $collection;
}
}
- Here,
$ids
is an array, which include category ids. $_productCollectionFactory
is an object of product collection factory which is used to get collection of product model.addCategoriesFilter
function to apply category filter.$collection
returns a collection of products which are assigned in given categories.
Step 2: Insert in phtml file
After the above step, you will have a collection in your block, now to get the Product collection in the block, follow the below snippet: Mageplaza/HelloWorld/view/frontend/templates/list.phtml
$ids = [1,2,3];
$categoryProducts = $block->getProductCollectionByCategories($ids);
foreach ($categoryProducts as $product) {
echo $product->getName() . ' - ' . $product->getProductUrl() . '<br />';
}
Step 3: Flush Cache & Test result
Now, let’s flush cache and test result.
Conclusion
Above are the three steps, which could help you get product collection by Category ID in Magento 2. I hope this post is helpful for you when obtaining product collection.
Enjoyed the tutorial? Spread it to your friends!
Featured Extensions







