Magento 2 Get Product Collection By Cetegory ID

Some time we need to get product collection for specific category id. So, in this article we'll discuss how to get category specific product collection in a block file and get that on phtml file.

Add below code in you block file to get category specific collection.

saveCopyzoom_out_map
namespace Devhooks\Module\Block; class Module extends \Magento\Framework\View\Element\Template { protected $productFactory; protected $categoryFactory; public function __construct( \Magento\Backend\Block\Template\Context $context, \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $productFactory, \Magento\Catalog\Model\CategoryFactory $categoryFactory array $data = [] ) { $this->productFactory = $productFactory; $this->categoryFactory = $categoryFactory; parent::__construct($context, $data); } public function getProductCollection() { $categoryId = '5'; $category = $this->categoryFactory->create()->load($categoryId); $collection = $this->productFactory->create(); $collection->addCategoryFilter($category); $collection->addAttributeToSelect('*'); $collection->addAttributeToFilter('status', \Magento\Catalog\Model\Product\Attribute\Source\Status::STATUS_ENABLED); $collection->addAttributeToFilter('visibility', \Magento\Catalog\Model\Product\Visibility::VISIBILITY_BOTH); return $collection; } }

In above code we use a static category id 5 but you can get is daynamic as per your need. Also, in above code have filtered the collection with Status and Visibility.

Now if you want get this collection in .phtml file then check the below code and call getProductCollection method in your phtml file.

saveCopyzoom_out_map
$productCollection = $block->getProductCollection(); foreach ($productCollection as $product) { echo "<pre>"; print_r($product->getData()); echo "</pre>"; }

Finally, we are done, let's flush or refresh cache and test the result.

That’s it.

I hope this post helped you to find what you were looking for. Bookmark it for your future reference. Do comment below if you have any other questions on that.

P.S. Do share this note with your team.

Review other articles maybe it'll help you too.




Recent Articles
Tags
Newsletter
Chrome Extension
Copyright © 2024 devhooks.in All rights reserved.
Ads OFF toggle_off
wifi_off