How to get products collection by category id in custom module

  1. Create a block call getProductCollection function.
  1. <?php
  2. /**
  3. * Abm
  4. *
  5. * Author : Tony Liu
  6. * Blog: https://www.tonyblog.cn
  7. *
  8. * DISCLAIMER
  9. *
  10. * Do not edit or add to this file if you wish to upgrade this extension to newer
  11. * version in the future.
  12. *
  13. * @package Tony_GetProductsByCategoryId
  14. */
  15. namespace Tony\GetProductsByCategoryId\Block;
  16. class GetProducts extends \Magento\Framework\View\Element\Template
  17. {
  18. protected $categoryFactory;
  19. public function __construct(
  20. \Magento\Framework\View\Element\Template\Context $context,
  21. \Magento\Catalog\Model\CategoryFactory $categoryFactory
  22. ) {
  23. $this->categoryFactory = $categoryFactory;
  24. parent::__construct($context);
  25. }
  26. public function getCategoryProduct($categoryId)
  27. {
  28. $category = $this->categoryFactory->create()->load($categoryId)->getProductCollection()->addAttributeToSelect('*');
  29. return $category;
  30. }
  31. }
  1. Show products in template.
  1. <?php
  2. /**
  3. * @var $block \Tony\GetProductsByCategoryId\Block\GetProducts
  4. */
  5. $categoryId = 5;
  6. $getProudctcollection = $block->getCategoryProduct($categoryId);
  7. ?>
  8. <ul class="category-products">
  9. <?php foreach ($getProudctcollection as $product) : ?>
  10. <li class="level0-child">
  11. <a href="<?php echo $product->getProductUrl(); ?>">
  12. <?php echo $product->getName();?>
  13. </a>
  14. </li>
  15. <?php endforeach;?>
  16. </ul>

If done this, you will see products of one category.
Tony's blog image

If you need full package, please go my github.
https://github.com/tonyabm/magento2-module-GetProductsByCategoryId