Magento 2: get product collection using category id
you can inject in your block an instance of \Magento\Catalog\Model\CategoryFactory
like this:
protected $categoryFactory;
public function __construct(
....
\Magento\Catalog\Model\CategoryFactory $categoryFactory,
...
){
...
$this->categoryFactory = $categoryFactory;
...
}
Then create this method in your block:
public function getCategory()
{
$categoryId = $this->getCategoryId();
$category = $this->categoryFactory->create()->load($categoryId);
return $category;
}
public function getProductCollection()
{
return $this->getCategory()->getProductCollection()->addAttributeToSelect('*');
}
Then you can use in the template this:
<?php foreach ($block->getProductCollection() as $product) : ?>
<!-- do something with $product -->
<?php endforeach;?>
You should be able now to just add this to your homepage content
{{block class="Block\Class\Name\Here" category_id="5" template="path/to/template.phtml"}}