Back to Top

Product Collection by Categories in Magento 2

Updated 21 February 2024

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.

Searching for an experienced
Magento 2 Company ?
Find out More

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

. . .

Leave a Comment

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


2 comments

  • jafar
  • Navin Bhudiya
  • Back to Top

    Message Sent!

    If you have more details or questions, you can reply to the received confirmation email.

    Back to Home