How to get products collection by category id in custom module
- Create a block call getProductCollection function.
<?php/*** Abm** Author : Tony Liu* Blog: https://www.tonyblog.cn** 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
tony
标签
热门文章
- 1 Magento ver. 2.2.0-dev - A technical prob... 16489
- 2 ECS git pull 代码很慢的问题 14622
- 3 玩客云监工客户端 13117
- 4 Magento 2 UI Form Validation 13039
- 5 Codeigniter SSL 强制重定向至https访问 12927
- 6 magento2 完整卸载模块的正确姿势 12565
- 7 Magento fix 500 12209
- 8 Magento index is locked by another reinde... 10657
- 9 Ubuntu删除日志文件 8936
- 10 Magento 2安装ElasticSearch 6.x搜索引擎-Ub... 8546
微信公众号