Magento 2: Get all Products of a Category

This article shows how we can get all products of a particular category in Magento 2.

Both Dependency Injection and Object Manager way of coding is shown below.

Using Dependency Injection (DI)

Below is a block class of my custom module (Chapagain_HelloWorld). I have injected object of \Magento\Catalog\Model\CategoryFactory class in the constructor of my module’s block class.

app/code/Chapagain/HelloWorld/Block/HelloWorld.php


<?php
namespace Chapagain\HelloWorld\Block;
class HelloWorld extends \Magento\Framework\View\Element\Template
{	
	protected $_categoryFactory;
		
	public function __construct(
		\Magento\Backend\Block\Template\Context $context,		
		\Magento\Catalog\Model\CategoryFactory $categoryFactory,
		array $data = []
	)
	{	
		$this->_categoryFactory = $categoryFactory;
		parent::__construct($context, $data);
	}
	
	public function getCategory($categoryId) 
	{
		$category = $this->_categoryFactory->create();
		$category->load($categoryId);
		return $category;
	}
	
	public function getCategoryProducts($categoryId) 
	{
		$products = $this->getCategory($categoryId)->getProductCollection();
		$products->addAttributeToSelect('*');
		return $products;
	}
}
?>

Now, we get products in a particular category and then print the product collection in our template (.phtml) file.


$categoryId = 6; // fetching products in category id 6
$categoryProducts = $block->getCategoryProducts($categoryId);
foreach ($categoryProducts as $product) {
	//print_r($product->getData());
	// printing category name and url
	echo $product->getName() . ' - ' . $product->getProductUrl() . '<br />';
}

Using Object Manager


$objectManager =  \Magento\Framework\App\ObjectManager::getInstance();		

$appState = $objectManager->get('\Magento\Framework\App\State');
$appState->setAreaCode('frontend');

$categoryFactory = $objectManager->get('\Magento\Catalog\Model\CategoryFactory');
$categoryHelper = $objectManager->get('\Magento\Catalog\Helper\Category');
$categoryRepository = $objectManager->get('\Magento\Catalog\Model\CategoryRepository');

$categoryId = 21; // YOUR CATEGORY ID
$category = $categoryFactory->create()->load($categoryId);

$categoryProducts = $category->getProductCollection()
							 ->addAttributeToSelect('*');
							 
foreach ($categoryProducts as $product) {
    //print_r($product->getData());
    // printing category name and url
    echo $product->getName() . ' - ' . $product->getProductUrl() . '<br />';
}

Hope this helps. Thanks.