Magento 2: How to Get Product Collection Filter by Category ID?

Magento 2: How to Get Product Collection Filter by Category ID?
A client can demand anything and as a Magento developer, you should know how to deliver it. One such demand could be “How to get product collection by Category ID in Magento 2”? Although this is not very common, you don’t know when a customer requires it. So here we are with the solution to Get Product Collection Filter by Category ID using Object Manager in Magento 2.

Get Product Collection from Single Category ID in Magento 2

The following is the example to get the list of products from one category with details like product name, url, price etc. in Magento 2 using Object Manager.
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
 
$categoryId = 10;
$categoryFactory = $objectManager->get('\Magento\Catalog\Model\CategoryFactory')->create();
$category = $categoryFactory->load($categoryId);
 
$products = $category->getProductCollection()
                    ->addAttributeToSelect('*');
 
foreach ($products as $product) {
    echo $product->getId() . "<br />";

        echo $product->getName() . "<br />";

        echo $product->getProductUrl() . "<br />"; 

}

Get Product Collection from Multiple Category ID’s in Magento 2

If you want to get product collection from multiple category ids, apply the following code.
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
 
$ids = [7,8,9];
$collectionFactory = $objectManager->get('\Magento\Catalog\Model\ResourceModel\Product\CollectionFactory')->create();
$products = $collectionFactory->addAttributeToSelect('*')
                            ->addCategoriesFilter(['in' => $ids]);
 
foreach ($products as $product) {
    echo $product->getId() . "<br />";

        echo $product->getName() . "<br />";

        echo $product->getProductUrl() . "<br />"; 
 
}

This is as simple as that. If you have any questions or need help, please don’t hesitate to contact our support team.

Related Articles: