In this tutorial we learn how to load product by category id.
For that we use \Magento\Catalog\Model\CategoryFactory.
Below is block file where we put our code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
<?php namespace Arpitk\Productbycategory\Block; class Productbycategory 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 getCategoryProducts($categoryId) { $data = $this->_categoryFactory->create(); $data->load($categoryId); $products = $data->getProductCollection(); $products->addAttributeToSelect('*'); return $products; } } ?> |
Now add below code to related .phtml file.
1 2 3 4 5 6 |
$categoryId = 4; $categoryProducts = $block->getCategoryProducts($categoryId); foreach ($categoryProducts as $product) { //print_r($product->getData()); echo $product->getName(); } |
Welcome to our blog!