- Create a block call getProductCollection function.
<?php/*** Abm** Author : Tony Liu* Blog: https://www.abmbio.xin** DISCLAIMER** Do not edit or add to this file if you wish to upgrade this extension to newer* version in the future.** @package Tony_GetProductsByCategoryId*/namespace Tony\GetProductsByCategoryId\Block;class GetProducts extends \Magento\Framework\View\Element\Template{protected $categoryFactory;public function __construct(\Magento\Framework\View\Element\Template\Context $context,\Magento\Catalog\Model\CategoryFactory $categoryFactory) {$this->categoryFactory = $categoryFactory;parent::__construct($context);}public function getCategoryProduct($categoryId){$category = $this->categoryFactory->create()->load($categoryId)->getProductCollection()->addAttributeToSelect('*');return $category;}}
- Show products in template.
<?php/*** @var $block \Tony\GetProductsByCategoryId\Block\GetProducts*/$categoryId = 5;$getProudctcollection = $block->getCategoryProduct($categoryId);?><ul class="category-products"><?php foreach ($getProudctcollection as $product) : ?><li class="level0-child"><a href="<?php echo $product->getProductUrl(); ?>"><?php echo $product->getName();?></a></li><?php endforeach;?></ul>
If done this, you will see products of one category.
If you need full package, please go my github.
https://github.com/tonyabm/magento2-module-GetProductsByCategoryId
