Product Collection by Categories in Magento 2
Here we are discussing how to get the collection of products assigned to any categories.
To get a product collection you can use the following code:
<?php
namespace Webkul\Test\Helper;
class Data extends \Magento\Framework\App\Helper\AbstractHelper
{
/**
* @var \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory
*/
protected $_productCollectionFactory;
public function __construct(
\Magento\Framework\App\Helper\Context $context,
\Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $productCollectionFactory
) {
parent::__construct($context);
$this->_productCollectionFactory = $productCollectionFactory;
}
public function getProductCollectionByCategories()
{
$categories = [2,3,5];//category ids array
$collection = $this->_productCollectionFactory->create();
$collection->addAttributeToSelect('*');
$collection->addCategoriesFilter(['in' => $categories]);
return $collection;
}
}
Here, $categories is an array, that includes category IDs.
$_productCollectionFactory is an object of the product collection factory that is used to get the collection of the product model.
addCategoriesFilter function to apply category filter.
$collection returns a collection of products that are assigned to given categories.
I hope this blog will help you with Product Category Collection in Magento 2. You may also check our wide range of best Magento 2 Extensions.
Please reach out to our team via a support ticket if you have any queries.
Try this and if you have any queries then just comment below 🙂
Categories:
Magento2
View Comments (2)
Comment or Ask a Question
Quick Links