How to Get Product Collection by Category ID in Magento 2

Steps to get Product Collection by Category ID

Create Products.php block

Directory

VendorName/ModuleName/Block/Products.php

Content for this file

<?php
namespace VendorName\ModuleName\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;
    }
}

 

Insert in phtml file

Directory

VendorName/ModuleName/view/frontend/templates/list.phtml

Content for this file

$ids = [1,2,3];
$categoryProducts = $block->getProductCollectionByCategories($ids);
foreach ($categoryProducts as $product) {
    echo $product->getName() . ' - ' . $product->getProductUrl() . '<br />';
}

 

Flush Cache & Check result

Now flush or clear the cache to check the result, the command:

php bin/magento cache:clear

 

If you are looking for Magento Developers, visit Magento Web Agency.