Get Product Collection by Category ID in Magento

As a developer, you usually have to do plenty of mundane tasks. They would require a lot of time if you hadn't known any tricks to process big amounts of information faster. One of those tasks is getting product collection by category ID for either related products or price updating, etc. 

Whatever the cause, you have to know how to get product collection by category ID in Magento. 

To get product collection by category ID: 

Get Product Collection by Category ID Using Class Construct

/**
* @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 getProductCollectionByCategoryIds($ids)
{
$collection = $this->_productCollectionFactory->create();
$collection->addAttributeToSelect('*');
$collection->addCategoriesFilter(['in' => $ids]);
return $collection;
}

where

  • $ids — array with the category IDs.
  • $_productCollectionFactory — object of product collection factory used to get a collection of the product model.
  • addCategoriesFilter — function that applies category filter.
  • $collection — returns a collection of products from given categories

then use

$ids = [6,29,350];
$categoryProducts = $this->getProductCollectionByCategoryIds($ids);

foreach ($categoryProducts as $product) {
    echo $product->getName() . ' - ' . $product->getProductUrl() . PHP_EOL;
}

Get Product Collection by Category ID Using Object Manager

Go get products collection by category ID with object manager:

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$_productCollectionFactory = $objectManager->create(\Magento\Catalog\Model\ResourceModel\Product\CollectionFactory::class);

$categoryIds = [9];

$collection = $_productCollectionFactory->create();
$collection->addAttributeToSelect('*');
$collection->addCategoriesFilter(['in' => $categoryIds]);

foreach ($collection as $product) {
    print_r($product->getData());
}

Magento development is easy if you know what tools to use to make your development more effective. Now that you know how to get product collection by category ID, you can go on and display it wherever you need.